Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
google OAuth2.0 Authentication before access to google Apis data in django
I am on a web application in which I login using email etc (Not through google auth) . but Now into dashboard I want a button which will ask for authentication and will give access to google api's data after authentication. till now I just got that this packadge will do this pip install social-auth-app-django but its just on login for user etc or signup . -
A form for editing the objects (tags) in a many-to-many relationship? (Django)
I have a model Post and a model Tag. Each post can have multiple related tags. class Post(models.Model): title = models.CharField() url = models.CharField() class Tag(models.Model): post= models.ForeignKey('my_app.Post', on_delete=models.CASCADE, related_name='tags') tag_text = models.CharField() I want to create a form so as to be able to edit the existing tags of a single post as a string delimited by commas. I know how to get the tags of a post as a list and turn the list into a string and vice versa, but I'm unsure how to create a new form for that. -
Problems with custom field that stores pks, and returns a queryset
I tried creating a custom field that would store a string that was a list of pks, then return that as a queryset. (yes, I could probably have done it using a many2many field, but I was (am) trying to reduce the number of db queries for this. In any case, all seems to work OK until I implemented a def pre_save(self, model_instance, add) method on my custom field. What seems to be happening is that when the queryset comes back from the pre-save, it is run through the SQLInsertCompiler.prepare_value, which checks the value to see if it has a "resolve_expression" attrubute, which it assumes is then a SQL expression and then tries checking for "contains_column_references"... The QuerySet object DOES have the "resolve_expression" attribute, but does NOT have the others that are in the SQL expression objects. I suspect this doesn't come up much. Any ideas on how to avoid this? is there a way of keeping the data as a string for longer and just converting it to a queryset right before returning it to the requesting code? class PkListField(Field): empty_strings_allowed = False description = "PK List" default_error_messages = {} def __init__(self, *args, max_recs=100, max_pk_size=5, sep=',', ordered=None, as_pks=True, model=None, … -
Where can I efficiently access model fields using a model object for Django query optimization
I have a model named Store. Other models like Image, Promotion, Keyword, they reference Store with ForeignKey or ManyToManyField. I'm confused which level is the most efficient to access Store's fields between HTML template level or views.py level. ------------------------------------------------------------------------------------------------------------------------------------ HTML template level, basically, only store object is passed. All the fields in store ojbect are accessed through the object on HTML templates. For me, I feel like this way has better organized code. Since I don't need to process all the fields I need separately one by one in views.py. HTML <h1>{{ store.name }}</h1> {% for img in store.image_set.all %} {% if forloop.counter < 5 %} ...Do something with img {% endif %} {% endfor %} {% for keyword in store.keyword_set.all %} ...Do something with keyword {% endfor %} {% for promo in store.promotion_set.all %} ...Do something with promo {% endfor %} views.py class StoreDetailView(View): def get(self, request, *args, **kwargs): ... store_id = self.kwargs['store_id'] store = Store.objects.get(id=store_id) store_images = store.image_set.all() ... context = { 'store': store, 'store_images': store_images, } return render(request, template, context) ------------------------------------------------------------------------------------------------------------------------------------ views.py level, unlike the above way, store object doesn't need to be passed directly to the template. Instead, store object is created to access fields in … -
Django mongo filter based on distinct foreignkey
I'm trying to retrieve all the results with certain severity ex ['high', 'medium', 'low'] I would be able to view a report's results whose rules match a certain severity. The select dropdown (single select) options should be generated based on the the available severities for that report. The severity field is a member of the Rule table. The filter relationship looks like result => rule => severity. models.Result.objects.filter(report=self.report) .distinct("rule") .values_list("rule", flat=True) I am not sure where to go from here. class Result(models.Model): report = models.ForeignKey(Report, related_name="results", db_index=False) rule = models.ForeignKey(Rule, related_name="results", db_index=False) class Rule(models.Model): severity = models.CharField(max_length=20, choices=RULE_SEVERITY_CHOICES, default="low") -
Django Count and Sum annotations interfere with each other
While constructing a complexe QuerySet with several annotations, I ran into an issue that I could reproduce with the following simple setup. Here are the models: class Player(models.Model): name = models.CharField(max_length=200) class Unit(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE, related_name='unit_set') rarity = models.IntegerField() class Weapon(models.Model): unit = models.ForeignKey(Unit, on_delete=models.CASCADE, related_name='weapon_set') With my test database, I obtain the following (correct) results: Player.objects.annotate(weapon_count=Count('unit_set__weapon_set')) [{'id': 1, 'name': 'James', 'weapon_count': 23}, {'id': 2, 'name': 'Max', 'weapon_count': 41}, {'id': 3, 'name': 'Bob', 'weapon_count': 26}] Player.objects.annotate(rarity_sum=Sum('unit_set__rarity')) [{'id': 1, 'name': 'James', 'rarity_sum': 42}, {'id': 2, 'name': 'Max', 'rarity_sum': 89}, {'id': 3, 'name': 'Bob', 'rarity_sum': 67}] If I now combine both annotations in the same QuerySet, I obtain a different (inaccurate) results: Player.objects.annotate( weapon_count=Count('unit_set__weapon_set', distinct=True), rarity_sum=Sum('unit_set__rarity')) [{'id': 1, 'name': 'James', 'weapon_count': 23, 'rarity_sum': 99}, {'id': 2, 'name': 'Max', 'weapon_count': 41, 'rarity_sum': 183}, {'id': 3, 'name': 'Bob', 'weapon_count': 26, 'rarity_sum': 113}] Notice how rarity_sum have now different values than before. Removing distinct=True does not affect the result. I also tried to use the DistinctSum function from this answer, in which case all rarity_sum are set to 18 (also inaccurate). Why is this? How can I combine both annotations in the same QuerySet? -
How to show a preview of user submitted website in an iframe or localhost?
I have been trying to figure out how to display code submitted by a user (html, css, javascript) on my Django website. I can get a single page application to show up in an iframe just fine, such as one html file with css and javascript files linked. The problem arises when the user has multiple html pages and wants to link between them. I haven't figured out how to support multiple html pages within an iframe. Is it possible to do this with an iframe? Can I set up a localhost environment on my Django application to run the user's website (similar to what CodeAcademy does)? How can I get this to work? -
Comparing two variables within HTML in Django
This is my HTML code : {% for divida in Contrato %} {% for empresa in Empresa %} <li> {{empresa.cnpj}} | {{divida.cnpj}} | {% if empresa.cnpj == divida.cnpj %} True {% else %} False {% endif %} </li> {% endfor %} {% endfor %} This is my result: 1.52136308000162 | 72718870000101 | False 2.05574445000107 | 72718870000101 | False 3.72718870000101 | 72718870000101 | False 4.52136308000162 | 05574445000107 | False 5.05574445000107 | 05574445000107 | False 6.72718870000101 | 05574445000107 | False 7.52136308000162 | 52136308000162 | False 8.05574445000107 | 52136308000162 | False 9.72718870000101 | 52136308000162 | False Lines 3, 5 and 7 should be True.. What am I missing? -
Allowing URL access only to logged-in users
I am getting started with the django framework and I created a simple website where the user first logs in and then is redirected to another page. I tried typing the URL of the redirected page before logging in, and it loads. Instead, I want it to redirect back to the login page (home page). I tried checking if the user is authenticated to view the page only if it is. It is written in the views.py file of the redirected page: def index(request): if request.user.is_authenticated(): return render(request, 'professors/index.html') else: return redirect('' % request) professors/ is the URL of the redirected page '' is the URL of the login page (home page) -
Django migrate fails when creating new table
We are fairly new to Django. We we have an app and a model. We'd like to add an 'Category' object to our model. We did that, and then ran 'python manage.py makemigrations'. We then deploy our code to a server running the older code, and run 'python manage.py migrate'. This throws 2 pages of exceptions, finishing with 'django.db.utils.ProgrammingError: (1146, "Table 'reporting.contact_category' doesn't exist")' This seems to be looking at our models.py. If we comment out Category from our model, and all references to it, the migration succeeds. I thought that the point of migrations is to make the database match what the model expects, but this seems to require that the model match the database before the migration. We clearly are doing something wrong, but what? -
DJango Template Not Found Issue
Still learning Django and for some reason I have difficulty grasping some concepts especially the url / template / view mappings. Attempting to reirect a FormView to a "Complete" page I have the following: urls.py from django.urls import path from .views import * urlpatterns = [ path('', IndexView.as_view(), name='index'), path('forgotid/', ForgotId.as_view(),name="forgotid"), path('forgotid/complete/',ForgotIdComplete.as_view(),name="forgotid_complete"), path('forgotpwd/', ForgotPwd.as_view(),name="forgotpwd") ] views.py from django.shortcuts import render from django.views.generic import FormView, TemplateView from .forms import LoginForm, ForgotIDForm class IndexView(FormView): template_name = "login/index.html" form_class = LoginForm class ForgotId(FormView): template_name = "login/forgotid.html" form_class = ForgotIDForm success_url = 'complete/' class ForgotIdComplete(TemplateView): template_name = "login/forgotid/complete/forgotid_complete.html" def get(self, request): return render(request, self.template_name, None) class ForgotPwd(TemplateView): template_name = "login/forgotpwd.html" submitting the ForgotID form should redirect me to the success_url but I get an error stating that the template could not be found. Can someone please explain what and why I am doing this incorrectly. -
Cannot save Django model with foreign key
I'm attempting to send a POST request from my frontend to add a new "Achievement" record. The achievement record has a foreign key field referring to a set, which contains many achievements. However, when I attempt to save, I get the error: "{"set": ["Incorrect type. Expected resource identifier object, received Set."]}" I don't know what a "resource identifier type" is and cannot find any docs on it by searching online. Here is my POST request data: {"achievement":{"title":"Rails is Omakase","description":"Lorem ipsum","experience":100,"set":"52"}} I've tried setting "set" to the id of the set and the "Set" serializer instance before saving. Serializers.py class SetSerializer(serializers.ModelSerializer): class Meta: model = Set fields = ('id', 'title', 'description') class AchievementSerializer(serializers.ModelSerializer): class Meta: model = Achievement fields = ('id', 'title', 'description', 'experience', 'set') models.py class Set(models.Model): title = models.CharField(max_length=100, blank=False) description = models.TextField() class JSONAPIMeta: resource_name = "sets" class Achievement(models.Model): title = models.CharField(max_length=100, blank=False) description = models.TextField() experience = models.IntegerField() set = models.ForeignKey(Set, on_delete=models.CASCADE, related_name="achievements") views.py class AchievementList(APIView): def post(self, request): data = request.data["achievement"] setId = data["set"] set = Set.objects.get(pk=setId) data["set"] = set serializer = AchievementSerializer(data=data) if serializer.is_valid(): serializer.save() return JsonResponse({"achievement":serializer.data}, safe=False) return JsonResponse(serializer.errors, status=400) -
Django Celery Task Model call returns 'str' object is not callable
Running into an odd issue that hasn't occurred in other projects with celery and django. I'm taking a JSON obj, iterating through it, and putting it into a django model, but can't create the model. tasks.py from __future__ import absolute_import, unicode_literals from myapp.celery import app from django.apps import apps from datetime import datetime from zeep import Client, Settings, helpers from zeep.wsse.username import UsernameToken from .models import * import pickle, json, copy class DateTimeEncoder(json.JSONEncoder): def default(self, o): if isinstance(o, datetime): return o.isoformat() return json.JSONEncoder.default(self, o) @app.task() def getProjects(): #dumpfile is a pickled zeep obj dumpfile = open('dump.txt','rb') getDataObjs = pickle.load(dumpfile) getDataObjsAsOrderedDict = helpers.serialize_object(getDataObjs) getDataObjsAsJson = json.loads(json.dumps(getDataObjsAsOrderedDict, cls=DateTimeEncoder)) for project in getDataObjsAsJson: try: new_project_project_key = int(copy.deepcopy(project['projectKey'])) print(new_project_project_key) print(type(new_project_project_key)) print(type(MyDjangoDBModel)) new_project_db_obj,created = MyDjangoDBModel.objects.get_or_create(project_key=new_project_project_key) print("HIT") This is what the logs return [2019-06-12 15:08:03,319: WARNING/ForkPoolWorker-4] 10836 [2019-06-12 15:08:03,319: WARNING/ForkPoolWorker-4] <class 'int'> [2019-06-12 15:08:03,319: WARNING/ForkPoolWorker-4] <class 'django.db.models.base.ModelBase'> [2019-06-12 15:08:03,321: WARNING/ForkPoolWorker-4] 'str' object is not callable I've also gotten the same error with MyDjangoModel = app.get_model('app name', 'model name'), the above is with direct import with from .models import *. The copy is more than likely unnecessary, though it was an attempt to work around the issue. -
Get update query when DEBUG is False, without affecting code execution
I would like to view the queries run inside a block of code, ideally getting it as a list of strings. Of course there are similar SO questions and answers, but they do not address my three specific requirements: Works for queries other than SELECT. Works when the code is not in DEBUG mode. The code executes normally, i.e. any production code runs as production code. What I have so far is a transaction inside a DEBUG=True override, that is instantly rolled back after the queries are collected. from contextlib import contextmanager from django.conf import settings from django.db import connections from django.db import transaction from django.test.utils import override_settings @contextmanager @override_settings(DEBUG=True) def print_query(): class OhNo(Exception): pass queries = [] try: with transaction.atomic(): yield for connection in connections: queries.extend(connections[connection].queries) print(queries) raise OhNo except OhNo: pass def do_special_debug_thing(): print('haha yes') with print_query(): Foo.objects.update(bar=1) if settings.DEBUG: do_special_debug_thing() There are two problems with that snippet: That DEBUG override doesn't do anything. The context manager prints out []. If the DEBUG override is effective, then do_special_debug_thing is called, which I do not want to happen. So, as far as I know, there is no way to collect all queries made inside a block of code, including … -
Tyring to group database results by age in Django
I want to get a count all the items in the database for a given user, grouped into buckets depending on a timestamp. I have a dictionary which defines a set of categories like this: age_categories = {'cat1': {'start': <timestamp>, 'end': <timestamp>}}, {'cat2': {'start': <timestamp>, 'end': <timestamp>}}, ... I want to get a result from the database that looks like this: User | cat1 | cat2 | cat3 | ... Joe Smith | 12 | 0 | 7 | ... Bob Smith | 4 | 9 | 11 | ... Based on this question, I've tried: age_query = [key=Count(Case(When(datefield__range=(val['start'], val['end']), then=1))) for key, val in age_categories.items()] ... results = Table.objects.filter(...).values(...).annotate(*age_query) but I can't get that to work. It gives me an invalid syntax error. If I change the query to be a list of strings as age_query = [key + "=Count(Case(When(datefield__range=('" + val['start'] + "', '" + val['end'] + "'), then=1)))" for key, val in age_categories.items()] it tells me that Complex annotations require an alias when the intent is that the dictionary key should be the alias. Is this achievable? I know how I'd do it in raw SQL, but I'd really rather use Django's tools if at all possible. … -
What does {$ ... $} stand for in django templates?
I have a Django App with an AngularJS (1.5.8) frontend and stumbled across a notation in the templates that I don't understand. I also can't find any explanation in the Django or AngularJS docs. <div class="form-label"> {$ ... $} </div> I know, that one can use {{ ... }} for variables or {% ... %} for tags or {# ... #} for comments. But what is {$ ... $} for? Any ideas? -
How to schedule Background Jobs in a multitenant App
I have a multitenant Django app app that allows tenants to schedule when the app should send invoices, send reminders, generate reports etc. Am using Celery for running background jobs but can switch to some other package if need be. Got two challenges. Which is the best way to setup the schedules and the other is how to take care of timezones. Scheduling Should I have a Database table which stores the details of the jobs (Type of Job, Time to run, Job Parameters etc) and then have a background job that queries this table say every 1 minute and if it finds Jobs that should have been run in the past 1 minute then it triggers the appropriate background job? I feel like that is inefficient? Is there a better way to do it? Currently got a few hundred tenants but I expect to get to about 15,000 tenants so my thinking is that this table might get very big and slow down the query time? Time Zones As for time zones, if a tenant is registered as being in GMT 0 and another is GMT+6, how do take care of that in scheduling the jobs so that clients … -
What Tool / App To Use For Running Django Function Periodically (Once A Day)?
Can you please recommend an app or a tool for Django 2.2 to run a function periodically? I have a list of products and want to update their price once a day. I've heard about Celery, but maybe there is something more simple that I can use? Thanks in advance. -
How do you get data from a many to many relationship that is connected with a cross reference table?
I am using the Django Rest Framework If you have the following models: class Table_B(models.Model): name = models.CharField(max_length=150, blank=True) class Table_C(models.Model): name = models.CharField(max_length=150, blank=True) class Table_A(models.Model): name = models.CharField(max_length=150, blank=True) table_b = models.ManyToManyField( Table_B, through='Table_AB', through_fields=('table_A_id', 'table_B_id') ) class Table_AB(models.Model): """A cross reference model""" table_A_id= models.ForeignKey(Table_A, on_delete=models.CASCADE) table_B_id = models.ForeignKey(Table_B, on_delete=models.CASCADE) field_1 = models.CharField(max_length=150, blank=True) field_2 = models.CharField(max_length=150, blank=True) table_c = models.ManyToManyField( Table_C, through='Table_ABC', through_fields=('table_AB_id', 'table_C_id') ) class Table_ABC(models.Model): """A cross reference model""" table_AB_id = models.ForeignKey(Table_AB, on_delete=models.CASCADE) table_C_id = models.ForeignKey(Table_C, on_delete=models.CASCADE) I also made a ERD to make it a bit more visual: So here is the questions that I couldn't get to work: How do I get the data from Table_A + Table_AB -> field_1 and field_2 + Table_C? I can't seem to understand how I should do this. -
Cannot resolve keyword 'content_type' into field. Choices are: app_label, comment, id, logentry, model, permission
What I am doing wrong here in views.py. After getting above stated error I tried comments = ContentType.objects.filter(model=content_type, id=object_id) and it didn't work either. def blog_detail(request, blog_slug): blog = get_object_or_404(Blog, slug=blog_slug) session_key = 'blog_views_{}'.format(blog.slug) if not request.session.get(session_key): blog.blog_views += 1 blog.save() request.session[session_key] = True content_type = ContentType.objects.get_for_model(Blog) object_id = blog.id comments = ContentType.objects.filter(content_type=content_type, object_id=object_id) context = { 'blog': blog, 'categories': get_category_count(), 'comments':comments, } return render(request, 'blogs/blog-detail.html', context) Thank you -
How do i fix an HTTP Error 401: Unauthorized when sending an email using sendgrid?
i want to write an application that send emails to users while using sendgrid,i have gone to sendgrid and followed all the instructions including installing sendgrid and setting the environmental variable. i have tried putting the environmental variable in the path but still shows the error i have also tried putting it in the code but still it fails with the same error this is my code of send-mail.py: import os from sendgrid import SendGridAPIClient from sendgrid.helpers.mail import Mail message = Mail( from_email='from_email@example.com', to_emails='to@example.com', subject='Sending with Twilio SendGrid is Fun', html_content='<strong>and easy to do anywhere, even with Python</strong>') try: sg = SendGridAPIClient(os.environ.get('SG.97- h52MJSXK4C7_FIl5yzw.q3GsOa4P_AO1pKvUcOzQg6XzuRXEY3mzD-Ci5eN2I2E')) response = sg.send(message) print(response.status_code) print(response.body) print(response.headers) except Exception as e: print(e ) i have created a folder called Mail and created a file inside named send_mail.py i expect to send an email but it throws a HTTP Error 401: Unauthorized -
Problema con la conexión Mysql -Python tratando de correr proyecto back desde local
Instale el MySQL Workbench y tengo un proyecto en python-django, el cual conecte con la base de datos que esta en MySQL, ya instale los componentes necesarios de gcloud components list, y los scripts de python pip para instalar el conector de python-mysql, pero al intentar correrlo desde local con el siguiente comando dev_appserver.py app.yaml alice.yaml nemesis.yaml jill.yaml me saca el siguiente problema: Traceback (most recent call last): File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine_python_runtime.py", line 96, in _run_file(file, globals()) File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine_python_runtime.py", line 90, in _run_file execfile(_PATHS.script_file(script_name), globals_) File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\runtime.py", line 28, in from google.appengine.api import rdbms_mysqldb File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\api\rdbms_mysqldb.py", line 74, in from MySQLdb import * AttributeError: 'module' object has no attribute 'NULL' ERROR 2019-06-12 08:46:39,513 instance.py:284] Cannot connect to the instance on localhost:23508 Traceback (most recent call last): File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine_python_runtime.py", line 96, in _run_file(file, globals()) File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine_python_runtime.py", line 90, in _run_file execfile(_PATHS.script_file(script_name), globals_) File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\tools\devappserver2\python\runtime\runtime.py", line 28, in from google.appengine.api import rdbms_mysqldb File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google\appengine\api\rdbms_mysqldb.py", line 74, in from MySQLdb import * AttributeError: 'module' object has no attribute 'NULL' ERROR 2019-06-12 09:00:01,493 instance.py:284] Cannot connect to the instance on localhost:17588 Traceback (most recent call last): File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine_python_runtime.py", line 96, in _run_file(file, globals()) File "C:\Users\user\AppData\Local\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine_python_runtime.py", line … -
Best way to manage user permission in Django Template (not in django admin)
I create 4 types of user and 1 module , 4 types users access their fields only view and update Suggest best method achieve -
How show phone_number in UserCreationForm in django?
I use AbstarctUser , now I will show phone_number field when creation new user in panel admin but does not show field models.py class User(AbstractUser): phone_number = PhoneNumberField(unique=True, verbose_name=_('phone number')) token_sms = models.CharField(verbose_name=_('token_sms'), max_length=125, null=True, blank=True) token_limit = models.IntegerField(verbose_name=_("token limit"), default=0, null=True, blank=True) complete_profile = models.BooleanField(verbose_name=_("complete profile"), default=False) REQUIRED_FIELDS = ['phone_number'] admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from orders.forms import UserCreationForm from orders.models import Order, User UserAdmin.fieldsets += ('Custom fields set', {'fields': ('phone_number', 'token_sms', 'token_limit', 'complete_profile')}), UserAdmin.readonly_fields += ('token_sms', 'token_limit') UserAdmin.add_form = UserCreationForm admin.site.register(User, UserAdmin) from django.contrib.auth.forms import UserCreationForm from phonenumber_field.formfields import PhoneNumberField from orders.models import User class CustomUserCreationForm(UserCreationForm): phone_number = PhoneNumberField() class Meta(UserCreationForm.Meta): model = User fields = UserCreationForm.Meta.fields + ('phone_number',) -
Best way to deserialize list of different objects in DRF?
API should accept a list of customers which are either persons or companies. They are similar objects but have some different fields. Example of json on input: { "customers": [{ "type": "person", "name": "Joe Smith" }, { "type": "company", "company_id": "123456780", } ] } What is the best way to write such Django Rest Framework's serializers which would correctly validate all fields in json objects?