Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Re-implementing Social Logins (in Django)
TL;DR: Is it OK to not store (Google/Facebook) OAuth2 access tokens, but rather request new ones on every login? I'll explain: To add social logins ("Login with Google/Facebook") to a Django app, you have Python Social Auth. The problem with it, at least for me, is that it's much more complicated than I'd like, requires a lot of configurations, creates additional tables in the database, and in general feels like a lot of moving parts I don't understand for a rather simple task. So, I read a bit about Google's and Facebook's flows, and they're simple enough: The server has an ID and a secret. The clients/users have their standard login credentials. Then: The server redirects the user to Google/Facebook, and provides its ID and a redirection URI. After the user has logged in, Google/Facebook redirects them to that URI with a code. The server sends its ID, secret, and the received code to Google/Facebook, and gets an access token in exchange, which it can now use to make API calls on behalf of the user. Even the most basic permissions are enough to query Google/Facebook for the user's email, which can then be matched against Django's standard User model … -
Adding data after submitting form in Django admin
(I'm newish to Django and using a codebase with Django 1.8) There's a model (Survey) which has a many to many relationship with another (Page) and a reference to a starting page (Page). Creating this in the admin panel would be really messy for the user, but it can be worked out if they make a few Yes/No decisions. So, in the admin add page I have added some select fields that are not part of the model (More or less 'Include Section A?' / 'Include Section B?' / 'Include Section C?'...etc), and based on what the user chooses here I want to add different keys to the page_links on Survey and the starting_page. Working these out is fine, but when the form / model is saved the page_links and start_page aren't there, presumably because they're not part of the form. I've tried adding them to cleaned_data (in save or clean) but that doesn't work. Here's the model: class Survey(models.Model): title = models.CharField(max_length=255) start_page = models.ForeignKey('Page', related_name='surveys_started', null=True) page_links = models.ManyToManyField('PageLink', related_name='surveys') and here's the Admin: class SurveyAdmin(admin.ModelAdmin): fieldsets = ( (None, { 'fields': ('title', ), }), ('User Decisions', { 'fields': ('do_a', 'do_b', 'do_c', ) }), ) form = SurveyForm … -
How to save a random item returned from QuerySet. Django, Python
I am trying to save the returned item from QuerySet, so that later it will display all the saved items in the next template. But I do not know how to go about it? 1.) Do I have to create a separate model for this? 2.) How do I transfer the result to be saved in the view? My models.py class City(models.Model): name = models.CharField(max_length=100) class User(models.Model): name = models.CharField(max_length=100) city = models.ForeignKey(City, on_delete=models.CASCADE) My views.py def random_views(request): shot = User.objects.all().order_by('?')[:1] #shot.pk = None '- it does not work' #shot.save() context = {'shot': shot} return render(request, 'index.html', context) -
Adding new Table on exsting database Django 1.8 on PostgreSQL
I try makemigration and migrate Here is error ProgrammingError at /admin/autoroni/autosalon/ relation "autoroni_autosalon" does not exist LINE 1: SELECT COUNT() AS "__count" FROM "autoroni_autosalon" ^ Request Method: GET Request URL: Django Version: 1.8.7 Exception Type: ProgrammingError Exception Value: relation "autoroni_autosalon" does not exist LINE 1: SELECT COUNT() AS "__count" FROM "autoroni_autosalon" -
How to show some news which is fetch from API in Django?
I request news from cryptocompare website with python request in django now when i load the json content it shows me all news but i want to show some news (like 6 articles for instance) in my page. Here I am pasting code please help me guys as I am new in Python and Django. rom django.shortcuts import render Create your views here. def home (request): import requests, json @ Crypto News api_requests = requests.get('@t api = json.loads(api_requests.content) return render(request,'home.html', {'api':api }) -
Which function in django.contrib.auth creates the default model permissions?
in the django documentation it says: These permissions will be created when you run manage.py migrate; the first time you run migrate after adding django.contrib.auth to INSTALLED_APPS, the default permissions will be created for all previously-installed models, as well as for any new models being installed at that time. Afterward, it will create default permissions for new models each time you run manage.py migrate (the function that creates permissions is connected to the post_migrate signal) It says that the function that creates these permissions is connceted to the post_migration signal. I was wondering which function is this because I need to make the default permissions programatically in my coode. -
Django - How to set up 2 models with the same fields?
I have a real estate app with 20 years of sales history. I want to put the last 2 years of listings into a model that will be actively queried, and the other 18 years into an archived model. I am using Django 1.11 with Postgresql 9.5 My limited database management knowledge tells me this is called 'horizontal partitioning' or 'sharding'. Is there a smart way to set this up in Django? Or do I simply copy and paste the same field names into both ListingActive and ListingArchive? class ListingActive(models.Model): data1 = models.IntegerField() data2 = models.CharField(max_length=10) ... data100 = models.CharField(max_length=20) class ListingArchived(models.Model): same fields as ListingActive -
Ajax e Djando select concatenate
I'm 'developing an app with Django 2.0> but I did not understand how to integrate Ajax. We would have to make a select chained in a form, to select regions and to select a region with the provinces. Data taken naturally from the database. I can not get out of it. Thanks in advance. -
Initial local Django mysql database
I have joined a team working on a Django project, and I am trying to setup the local mysql database schema. This project has existed for a long time, so there are existing migrations. I have created the empty database in mysql, but when I try to apply migrations to create the schema, it complains that the tables don't exist yet. $ ./manage.py migrate Traceback (most recent call last): File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/Users/rnapier/.pyenv/versions/api-3.6.6/lib/python3.6/site-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (1146, "Table 'api_test.headset_product' doesn't exist") I've also tried syncdb, migrate --run-syncdb, and makemigrations with the same results. I've also tried loaddata with our fixtures, with the same results. I've read Django : Table doesn't exist, but I didn't drop tables in this case (no tables have ever existed), and I don't want to recreate all the migrations (I'm not the only person … -
Ajax return full page
Ajax with Django didn't work properly well. It must be one page web app. I tried to make template for Calc as separate page but didn't working too. Urls.py urlpatterns = [ url(r'', views.main, name = 'main'), url(r'calc/$', views.calc, name = 'calc') ] Views.py def main(request): return render(request, 'main/index.html', context = { 'some': some } ) def calc(request): if request.GET: outputdata = request.GET('somedata') return HttpResponse(outputdata) index.html ... <div> <form action="{% url 'calc' %}" method="GET"> {% csrf_token %} <input type="text" id="someinput" value="somevalue"> </form> <button type="submit" id="somebutton">Button</button> </div> ... script.js $(document).ready(function() { $('#somebutton').on('click', function(event) { $.ajax({ type: 'GET', url: 'calc', data: { 'somedata': $('#someinput').val() }, success: function(data) { alert(data); } }); }); }); Alert Alert message -
django aggregating values from related table
I am using Django to serve REST APIs to my front end app. I have a SaleInvoice table and SaleLineItems table. I created a SerializerMethodField (sub_total) to calculate a value based on values in fields of SaleLineItems table. When I make a post/patch request to SaleLineItems, I am able to get the sub_total in response.data. Now, I need a grand_total in SaleInvoice table/serializer which can aggregate all sub_total values from SaleLineItems records which have the same Sale Invoice id. If I do SaleLineItems.objects.filter(sale_invoice=saleInvoiceId).aggregate(Sum('sub_total')) I get an error telling me that I cannot use 'sub_total' but can use other regular fields of the SaleLineItems table. Kindly help. models.py ... class SaleInvoice(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) serial_number = models.IntegerField(blank=True, null=True) amount_before_freight = models.FloatField(blank=True, null=True, default=0) freight = models.FloatField(blank=True, null=True, default=0) amount_after_freight = models.FloatField(blank=True, null=True, default=0) def __str__(self): return str(self.id) class SaleLineItems(models.Model): sale_invoice = models.ForeignKey(SaleInvoice, on_delete=models.CASCADE) product_name = models.ForeignKey(Product, on_delete=models.PROTECT) product_qty = models.FloatField() product_rate = models.FloatField(blank=True, null=True, default=0) product_disc = models.FloatField(blank=True, null=True, default=0) ... serializers.py ... class SaleLineItemsSerializer(serializers.ModelSerializer): def get_sub_total(self, instance): return ( Decimal(instance.product_qty) * Decimal(instance.product_rate) * Decimal(1-(instance.product_disc/100)) ).quantize(Decimal("1.00")) sub_total = serializers.SerializerMethodField() class Meta: model = SaleLineItems fields = "__all__" ... -
Django TypeError: int() argument must be a not 'set'
Сreated models: class Teacher(models.Model): name = models.CharField(max_length=200) def __str__(self): return self.name class Subject(models.Model): subject = models.CharField(max_length=200) teacher = models.ArrayReferenceField(to=Teacher) def __str__(self): return self.subject while trying to add to the Subject an error occurs: int() argument must be a string, a bytes-like object or a number, not 'set' Log: dpaste.com/3GWTC6P -
Django - Database design
Pretty simple and amateur question I imagine. I have the following database so far: Person model Student model inherits from Person, no added functionality Lecturer model same as Student Course model leader = ForeignKey to Lecturer (1 Lecturer can have many courses) students = ManytoMany with Student (Many students can take many courses) Card model student = OneToOne with student (1 card per 1 student). Event model course = ForeignKey to Course (One course can have many events) Now my question is; I want to mark students present in an event based on the following criteria. On creation of Event, marked students need to be empty. Later I will create a view that will register a Card ID. The Card model has a 1-1 relationship with student. Student is many-many with Course. Course is a FK to Event. They need to be part of the same course that the Event is connected to. The marked present students need to be visible inside the model later on. How do I go about doing this? -
ModuleNotFoundError: No module named 'project.user'
If anyone knows how to solve this, please don't hesitate to help. I've tried many hints, but so far this problem still remains. Too frustrating! I just started a little project on Django because I want to test Django Rest Framework. I created a project called project and inside it an app called user. After that, I created a directory called api inside user and then I created the files viewsets.py and serializers.py in order to test Django Rest Framework. In urls.py I imported "UsuarioViewSet" class from viewsets. from project.user.api.viewsets import UsuarioViewSet When I run python manage.py runserver the problem bellow ocurrs (I also tried only user.api.viewsets... but it says "unresolved reference") In my settings.py I registered 'user' and 'rest_framework': INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'user', ] OS: Linux Mint | IDE: PyCharm (community) | Virtualenv: venv | Python: 3.6.6 -
Django: Annotate sum on variable number of columns
So I've read the annotate columns, and utilizing the F() functions, and I saw this post on how to sum multiple columns. However, I'm working with an EAV style DB, so I'm given a variable list of columns. Consider the example: class TestModel(models.Model): column_a = models.FloatField() column_b = models.FloatField() column_c = models.FloatField() column_d = models.FloatField() ATTEMPT 1: columns = {'column_a', 'column_c', 'column_d'} queryset = DummyModel.objects.annotate(total=Sum([F(column_name) for column_name in columns])) However, a print(queryset.query) yields the error django.core.exceptions.FieldError: Cannot resolve expression type, unknown output_field ATTEMPT 2: queryset = DummyModel.objects.annotate(total=ExpressionWrapper(Sum([F(column_name) for column_name in columns]), output_field=FloatField())) This does not yield a compilation error, but the SQL query yields: SELECT "test_model"."column_a", "test_model"."column_c", "test_model"."column_d", SUM([]) AS "total" FROM "test_model" Which is empty. Does anyone have any idea of how to solve this? Any help is greatly appreciated! -
Proyecto en Django 2.1
Al ingresar al blog de mi proyecto, sale este error en el navegador: enter image description here -
Migrations not working when I tried to extend oauth 2 provider model
Here is the code I wrote to extend the oauth 2 provider model Application: from django.db import models from oauth2_provider.models import AbstractApplication class CustomApplication(AbstractApplication): application_foo = models.CharField(max_length=100, blank=True) But when I run makemigrations, no change is detected. -
Display all record on django-filter page startup
I have the inverse problem of Empty result list on django-filter page startup. I would like that on startup my view display all records before user can apply filter. I don't have (found in the reply of my linked question) : The problem is, the default view of a Filter is to return ALL the results. This is my view : class EntrepriseList(LoginRequiredMixin, SingleTableMixin, FilterView): table_class = EntrepriseTable model = Entreprise template_name = 'stage/entreprise_list.html' filterset_class = EntrepriseFilter paginate_by = 30 -
Django - Upload pdf file using EmailMessage
I am getting an error when i tried to send mail using django EmailMessage with attached file . ref: render_to_pdf from easy_pdf.rendering import render_to_pdf from django.core.mail.message import EmailMessage em = EmailMessage(subject, message, from_mail, to_mail) post_pdf = render_to_pdf('pdf_html.html', context) em.attach('file.pdf', post_pdf, 'application/pdf') em.send() Error : expected bytes-like object, not HttpResponse waiting for valuable response, thanks -
django UpdateView 'str' object has no attribute 'as_widget'
I am new to django and developing a small app in which i have to update a Project Model. I am using django builtin UpdateView to update the details of a project already saved. When i run this code it shows str object has no attribute 'as_widget Error. I think the form fields are going to the template as a string not as an object but i dont know why?. I only want to update certain fields of the model. that's why I've used "fields" in UpdateView. But I also tried form_class just to check but that didn't work either. I've been stuck on this bug for two days. Any help will be appreciated. Following is the project Model class Project(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=20 , unique=True) startDate = models.DateField(default=timezone.now) endDate = models.DateField() sourceOfProject = models.CharField(default='Website', verbose_name='Project Source',max_length=20 , choices=(('Website' , 'Website'),('Client','Client'))) # website or client etc sourceName = models.CharField(default='' , verbose_name='Source Name' , max_length=20) paymentType = models.CharField(default='Fixed' , verbose_name='Payment Type', max_length=20 , choices=(('Hourly','Hourly'),('Fixed','Fixed'))) # If True then hourly else fixed ProjectPaymentAmount = models.PositiveIntegerField(verbose_name='Amount') # this amount is according to hourlyPayment==True or False is_Active = models.BooleanField(default=True) projectSeverity = models.PositiveIntegerField(default=1, choices=SEVERITY_CHOICES) hubstaffName = models.CharField(max_length=30, null=True , default='') hoursToWork = … -
Deploying public Django project through Heroku Github pipeline without making credentials public
I have a Django project in a public repo. It is separately deployed on Heroku, I want to enable the github Heroku pipeline feature. However this will require me to put my credentials in the settings.py which will be available in the public repo. I have integrations like social-auth-app-django, django-storages which require secret keys. I found one blog which talks of putting only the credentials in a separate secret file but it won't work with the Heroku pipeline. Is there any way/tools to resolve this without actually making the repo private ? -
403 error loading static files in Bitnami @ google cloud for Django website Apache
Save me from Apache insanity. I have a Django site deployed in google cloud using Bitnami (Apache) and the templates load okay. The static files however return: Failed to load resource: the server responded with a status of 403 (Forbidden) The httpd-app.conf is as below: <IfDefine !IS_DJANGOSTACK_LOADED> Define IS_DJANGOSTACK_LOADED WSGIDaemonProcess wsgi-djangostack processes=2 threads=15 display-name=%{GROUP} </IfDefine> <Directory "/opt/bitnami/apps/django/django_projects/arbspiper/arbspiper"> Options +MultiViews AllowOverride All <IfVersion >= 2.3> Require all granted </IfVersion> WSGIProcessGroup wsgi-djangostack WSGIApplicationGroup %{GLOBAL} </Directory> Alias /static/ "/opt/bitnami/apps/django/django_projects/arbspiper/static" <Directory /opt/bitnami/apps/django/django_projects/arbspiper/static> <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> WSGIScriptAlias /arbspiper '/opt/bitnami/apps/django/django_projects/arbspiper/arbspiper/wsgi.py' the collected static is at /opt/bitnami/apps/django/django_projects/arbspiper/static i have tried every solution i have found, first i added <Directory /opt/bitnami/apps/django/django_projects/arbspiper/static> <IfVersion < 2.3 > Order allow,deny Allow from all </IfVersion> <IfVersion >= 2.3> Require all granted </IfVersion> </Directory> in httpd.conf in apache ... didnt work I then set permissions to project directory by: sudo chmod 775 /opt/bitnami/apps/django/django-projets/arbspiper sudo chown -R bitnami:daemon /opt/bitnami/apps/django/django-projets/arbspiper it didnt work either. Followed by a couple more which were basically somehow similar to this two. Thanks for your input in advance. All everyone wants is a beautiful site, why Apache oooh why. -
Using Django/Postgres get a calculated field which get a field value if exist if not another field value
I have a Django Model: Item(models.Model): url = models.URLField(blank=True, null=True) alt_url = models.URLField(blank=True, null=True) I want to do a select in the database to get a new variable which will have the value of url if url exist, if not get the value of alt url In pseudo-code: 'SELECT url=(url if url exist else alt_url) from item' -
Bulk, partial updates with Django Rest Framework
I want to partially-update multiple items at once. I've already added a mixin for allowing me to bulk-create (and that works well) but even though I've added a partial argument, it doesn't allow for patching a list. I'm guessing that this is a routing issue. I need a new view to handle PATCH on / (rather than /id/), but I'm well out of my depth. Existing answers for this don't work for 3.8, or at least haven't worked for me. What do I need to do to the following? class ResourceSerializer(serializers.ModelSerializer): class Meta: model = Resource fields = ('id', 'name', ...) read_only_fields = ('id',) class BulkMixin: def get_serializer(self, *args, **kwargs): if isinstance(kwargs.get('data', {}), list): kwargs['many'] = True kwargs['partial'] = True return super().get_serializer(*args, **kwargs) class ResourceViewSet(BulkMixin, viewsets.ModelViewSet): serializer_class = ResourceSerializer -
Django; get choices display value using enum as choices
I have a Django model in which I'm using the choices parameter. For the choices, I'm using a Python Enum. Now I want to display the choices display value in a template. I know there's .get_fieldname_display but it just returns the key instead of the display value in this case. Model: class LocalTitle(models.Model): type = models.CharField(max_length=8, choices=[(tag, tag.value) for tag in LocalTitleCodes]) title = models.CharField(max_length=255) Enum: class LocalTitleCodes(Enum): title_00 = 'Japanese' title_01 = 'English' title_02 = 'French' So in my case, if I do title.get_type_display in my template it returns title_00 and not Japanese. How can I get the display value? If it matters, I'm using Django 2.1 and Python 3.6.