Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to store historical data using Django
I am new to Django and am trying to figure out how to store historical data and be able to reference any data point from a date in the past. Say I want to store data on a kids height change as he grows and be able to compare his height at day 400 to his height at day 6xx. How would I set this up in Django? Would there need to be a foreign key relationship between height and the kid? -
Migrated from Django 1.11 to 2.1.4, Options requests giving 403
I Migrated my python codebase from Django 1.11 to 2.1.4, while updating python from 2.7 to 3.7. After resolving many code-level issues, now everything is working fine. When I am testing to GET data from the postman, it works perfectly. However, when I try to get it using my frontend code, it first sends options requests, which is failing, giving 403. So, backed sends nothing. Do I need to change any default Django settings to make options requests work like before? -
I'm updating my pg_hba.conf, but the file gets reset to default everyday
I've made my django instance accessible on pg_hba.conf. But every morning when I go to get started, I have to re-apply the changes because the file has reset back to its original content. This is a CentOS7 Server running Apache with cpanel, the django instance is setup with gunicorn and nginx on a separate port from Apache's httpd. I've applied the changes to pg_hba.conf and issued the following commands but they do not fix the issue. sudo systemctl restart postgresql sudo service postgresql restart here is the code I placed into pg_hba file: local all all peer host all all 165.227.123.167/32 md5 host all all ::1/128 md5 #That code successfully allows access to database once applied to file and this command following: sudo systemctl restart postgresql I expected the change to be permanent, but it actually needs to be done daily. -
Social Token failed to get expires_at field when using https.
When tried to add Facebook Account, expire date of access token is empty. django-allauth==0.38.0 Django 2.0 Python 3.6 -
Display Count of Foreign key in Other table
i want to display number of Users in that company for all companies. I am using User in-built Model. UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) Company Model class Company(models.Model): company_name = models.CharField(max_length=20, unique=True) company_description = models.CharField(max_length=100) View to display Companies class CompanyListView(LoginRequiredMixin, generic.TemplateView): template_name = 'company/company.html' def get_context_data(self, **kwargs): context = super(CompanyListView, self).get_context_data(**kwargs) context['companies'] = Company.objects.all() # Count of Users return context Display Count of Users for each company in single template -
Django: Tree stored in DB, derive JSON
I have a model like so: class Node(models.Model): parent = models.ForeignKey(Node, null=True) Let us assume I have the following tree stored using this DB structure: Tree Structure What is the most efficient way to obtain a JSON in the following structure, in a query written in Django's ORM? {"node": "A", "children": [ {"node": "B2", "children": [ {"node": "C1", "children": []}, {"node": "C2", "children": []} ]}, {"node": "B1", "children": []} ]} -
Heroku error 500 when running django raw query
I'm executing a raw query in django and it works fine. But when I deployed it on heroku I'm getting an error. Maybe it's happeninig because on heroku is running postgree, and I did the query to run on sqlite. If I'm right, which changes must I do in my query to works well? cursor = connection.cursor() cursor.execute('''select l_article.id, l_article.lei_id, l_article.article, l_article.is_titulo, laws_marcacao.is_marcado, laws_marcacao.description, laws_marcacao.votos, accounts_user.id , laws_marcacao.description from l_article inner join accounts_user left join laws_marcacao ON laws_marcacao.article_id = l_article.id and laws_marcacao.user_id = accounts_user.id where l_article.law_id = %s and accounts_user.id = %s;''', [law.id, request.user.id]) data = cursor.fetchall() That's the error: Traceback (most recent call last): File "/app/.heroku/python/lib/python3.7/site-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) psycopg2.ProgrammingError: syntax error at or near "where" LINE 5: where l_article.law_id = 1 and acco... -
Dynamic Bootstrap Modal URL
I have a datatable with information, and I want to be able to select an item, and click a button to update that table. Functionality seems to work, however, the issue is passing formURL an url that changes based on what the user have selected. I tried to do some dirty work and assign an onclick function to the button and call the Modalform everytime, it kinda worked. Except, you had to click multiple times before it actually updated to the newly selected item. Just assume that the getID() function knows how to get ID from the currently selected item. <button class="uppdatera-produkt btn btn-primary" type="button" name="button">Uppdatera Produkt</button> <script> $(document).ready(function() { $(".create-produkt").modalForm({ formURL: "{% url 'create_produkt' %}" }); $(".update-produkt").modalForm({ formURL: "{% url 'update_produkt' 12345 %}".replace(/12345/, getID()) }); table = $('#storage').DataTable( { }); $('#storage tbody').on( 'click', 'tr', function () { if ( $(this).hasClass('selected') ) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); id = table.row('.selected').data()['id']; } } ); </script> -
How to get data from the query set returned from elasticsearch django
I am trying to get data from elastic search in my application but its returning a query set which triggers an error in my serializers "Expected a list of items but got type \"Search\".". And when I print results returned from elastic search i get <django_elasticsearch_dsl.search.Search object at 0x1101f2b00>. I haven't used elastic search before and its giving hell... document.py from django_elasticsearch_dsl import DocType, Index, fields from elasticsearch_dsl import analyzer from .models import Unit, Rental units = Index('units') html_strip = analyzer( 'html_strip', tokenizer="standard", filter=["standard", "lowercase", "stop", "snowball"], char_filter=["html_strip"] ) @units.doc_type class UnitDocument(DocType): rental = fields.ObjectField(properties={ 'property_type': fields.TextField(), 'city': fields.TextField(), }) class Meta: model = Unit fields = [ 'bedroom', 'bathroom', 'price', ] related_models = [Rental] def get_queryset(self): """Not mandatory but to improve performance we can select related in one sql request""" return super(UnitDocument, self).get_queryset().select_related( 'rental' ) def get_instances_from_related(self, related_instance): """If related_models is set, define how to retrieve the unit instance(s) from the related model. The related_models option should be used with caution because it can lead in the index to the updating of a lot of items. """ if isinstance(related_instance, Rental): return related_instance.car_set.all() In my views.py i have tried to capture the anticipated data. views.py class SearchView(APIView): permission_classes = (AllowAny,) … -
Django Rest Framework different serializers for on model
I have Model, like: def SomeModel(models.Model): serial_num = models.IntegerField(unique=True) count = models.IntegerField() And have to create 2 url which will work with this model. But, there are have to be 2 different serializers. For example: For first url user’data have to has both fileds (serial_num and count) For second url users’data have to has only one field (count). In second case serial_num will be generated in Serializers class. Is this good practice to make 2 different serializers for one model? And also question, what about validation? Field “count” is depends on another model. I thought put validate into serializer class. But I don’t want to have 2 the same blocks of validation code in 2 different serializers classes (for both urls). -
ERROR: ERROR: Could not find a version that matches djangomysqlrestframework
I am trying to install djangomysqlrest framework in my django project which is created inside pipenv. i tried the following command: pipenv install djangorestframework pipenv install djangomysqlrestframework but in both cases it is giving following error: x Locking Failed! .... .... ERROR: ERROR: Could not find a version that matches djangomysqlrestframework -
How do I set a ForeignKey based on the user account when I save a new element with the extra field of modelformset_factory?
I have two problems: 1) I would like to add a new player in extra field of the Formset but when I save it I have an IntegrityError because team = models.ForeignKey(Team, on_delete=models.CASCADE is not set. I need that the value of team is team=request.user.team but I don't know where to put this in my views.py or if I need to override some existing function. 2) When I render the site at the end of each form appear the string "Human ptr:"... how can I delete it? I have a form made with formset_factory rendered like this: team_area.html {% extends 'base_layout.html' %} {% block content %} <h1>Area Squadra</h1> <form method="post" action=""> {% csrf_token %} {{ player_formset.management_form }} {% for player_form in player_formset %} {% for field in player_form %} {{ field.label_tag }} {{ field }} {% endfor %} <br> {% endfor %} <input type="submit" value="Aggiorna"> </form> {% endblock %} And the view is managed by: views.py from django.shortcuts import render, redirect from skeleton.models import Player from django.contrib.auth.decorators import login_required from .forms import PlayerForm from django.forms import modelformset_factory # Create your views here. @login_required(login_url="/accounts/login/") def team_area(request): PlayerFormSet = modelformset_factory(Player, fields=('first_name', 'last_name'), extra=1) if request.method == "POST": player_formset = PlayerFormSet( request.POST, request.FILES, … -
Bitnami Django stack deploying an existing project issue
I am bit new to Bitnami django stack which I found is really useful to deploy a django project with much hassles. I have a project which is build in django so for deploying the project I tried to install the stack by downloading the bitnami django stack even though the installation went without error and was able to start the apache server the deployment of existing project seems to be throwing error. I tried the exact steps from https://docs.bitnami.com/oci/infrastructure/django/get-started/deploy-django-project/ but seems like it doesnot have full documentation for deploying existing project . It shows how to create a new project and run it. so I tried by replacing the demo project with the new project which i had created earlier that to went wrong by not working. So my question here is : How to deploy exactly in django stack for existing project ? How to install requirements to the python path(for that I found use_django_stack script but bit confused with the usage) ? How to migrate models ? How to activate virtualenv ? -
Django REST Framework, save to extra field on custom user model
Using Django REST Framework (DRF) I added a custom user model with one extra field. I have posted my code at the bottom. Now, when registering a new user ('/rest-auth/registration/') using DRF's graphical interface, I do get an extra input for the new model field. When I enter a value into this form input and hit POST, a new user is indeed created, but the extra field stays empty. I have been looking into how to get this to work, and found another SO question with a good example and answers, but the problem with this SO post is that the poster uses AbstractBaseUser as the class that his custom user models inherits from, and I want to use AbstractUser instead. (Why? Since I read that this is recommended, unless you truly understand what you are doing.) Because the poster in the other SO answer uses AbstractBaseUser, his solution seems to involve much more code and compliation than I need. So, can anyone tell advice me on how I can have the extra field also be filled during registration, when POSTing the correct data? users.models.py: from django.contrib.auth.models import AbstractUser from django.db import models class CustomUser(AbstractUser): preferred_locale = models.CharField(max_length=2, blank=True, null=True) … -
Django REST-Auth Password Reset Tokengenerator (Generates b36 uid on request, wants b64 uid on confirm)
I am completely confused by the django middleware available: I simply want to get password-reset (and later password-change) functionality running, using django with rest_auth on the backend and Vue on the frontend. Step 1: Requesting the Reset-Link via Mail Views So far I have made a CustomPasswordResetView: # project/accounts/views.py from rest_auth.views import PasswordResetView class CustomPasswordResetView(PasswordResetView): pass Serializers and a CustomPasswordResetSerializer: # project/accounts/serializers.py from rest_auth.serializers import PasswordResetSerializer class CustomPasswordResetSerializer(PasswordResetSerializer): email = serializers.EmailField() password_reset_form_class = ResetPasswordForm def validate_email(self, value): # Create PasswordResetForm with the serializer self.reset_form = self.password_reset_form_class(data=self.initial_data) if not self.reset_form.is_valid(): raise serializers.ValidationError(self.reset_form.errors) ###### FILTER YOUR USER MODEL ###### if not get_user_model().objects.filter(email=value).exists(): raise serializers.ValidationError(_('Invalid e-mail address')) return value def save(self): request = self.context.get('request') # Set some values to trigger the send_email method. opts = { 'use_https': request.is_secure(), 'from_email': getattr(settings, 'DEFAULT_FROM_EMAIL'), 'request': request, } opts.update(self.get_email_options()) self.reset_form.save(**opts) Settings.py In the settings.py I have these fields, which seem relevant to me for my problem: # project/vuedj/settings.py REST_AUTH_SERIALIZERS = { "USER_DETAILS_SERIALIZER": "accounts.serializers.CustomUserDetailsSerializer", "LOGIN_SERIALIZER": "accounts.serializers.CustomUserLoginSerializer", "PASSWORD_RESET_SERIALIZER": "accounts.serializers.CustomPasswordResetSerializer" } (The complete settings.py is attached at the bottom) URL patterns My urls already catch my API request in order to send the Password-Reset Email: # project/vuedj/settings.py urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/', include('api.urls')), path('accounts/', include('allauth.urls')), path('', api_views.index, name='home') ] … -
How to Access Data of Models of OneToOneFiled Django ORM
I am using User in-built model. Now i am query in UserListView to exclude all users who is Super Admin where Role is stored in Roles Model. I dont know how to query queryset = User.objects.exclude(user_user_role_id=1) This is problem please help me to Query class UserListView(LoginRequiredMixin, generic.ListView): model = User template_name = 'users/users.html' context_object_name = 'users' queryset = User.objects.exclude(user_user_role_id=1) UserProfile Model class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) user_company = models.ForeignKey(Company, on_delete=models.CASCADE) user_role = models.ForeignKey(Roles, on_delete=models.CASCADE) class Roles(models.Model): role_title = models.CharField(max_length=30) role_description = models.CharField(max_length=100) -
Bulk create items in Django CreateView
I would like to try add rows in template and then save it. In template, click "add rows" button will generate a new row and "submit" is save this form. What I want to do is user can add number of row and save it. But in CreateView, it's always only got the first row. I have try lots of ways but still have no idea. Here is my template: <form method="post" class="uniForm" action=""> {% csrf_token %} <table class="table table-striped table-condensed" id="dyeing"> <thead> <tr> <th>choice</th> <th>number</th> <th>ticket</th> </tr> </thead> <tbody> <tr> <th><input type="checkbox" name="record"></th> <th><p id="counter"> 1 </p></th> <th>...</th> </tr> </tbody> </table> <div class="col-sm-12"> <input type="button" id="btn" value="add"/> </div> <div class="col-sm-12"> <input type="submit" value=" save" class=""> </div> </form> and jQuery part is: <script> $("#btn").click(function () { //var markup = "<tr><td><input type='checkbox' name=' addrow($('#dyeing > tbody:last-child')) }); function addrow(selector) { new_row = selector.clone(true) counter = parseInt(new_row.find('#counter').text(), 10) + 1 new_row.find(":input").each(function () { var name = $(this).attr('name'); if (counter == 2) { name = name + '-' + counter } else { name.replace('-' + (counter - 1), '-' + counter) } var id = 'id_' + name; $(this).attr({'name': name, 'id': id}) }) new_row.find('#counter').text(counter) selector.after(new_row) counter++ } my views.py: class CreateTicketForm(generic.CreateView): ... def … -
How do I override the .update() method inside a custom manager class
How can I override the update() method of a django model inside a custom manager? I would like to modify the behavior of some methods(all(), update(), filter()) of a django model and I have tried to override using what my code down here suggests but nothing is happening. I have tried using QuerySet instead of inheriting from Manager but I am failing to override it properly as I am getting empty results all over the system. class undeletedObjectManager(models.Manager): def get_queryset(self): return super(undeletedObjectManager, self).get_queryset().filter(deleted=False) def update(self, *args, **kwargs): if "deleted" in args: # some logic here super().update(*args, **kwargs) the update() method isn't reached and I am guessing it is because I am not overriding the correct member. Is there a specific method name? in both Manager and QuerySet classes? How should I override them? -
How to Exclude Specific Content by Tag in Django RSS Feed
I'd like to exclude specific articles from my feed based on their tag. In the following case I'd like to exclude all articles that are tagged Exclude Article. model.py tags = models.ManyToManyField(Tag, blank=True, related_name='tagged') feed.py def items(self, item): return Article.published().all().exclude(tags__name=["Exclude Article"])[:5] -
Problem using ArrayReferenceField with djongo and django
I'am trying to create an application with django using djongo to communicate with mongodb. I have the following model: from djongo import models from django import forms class Blog(models.Model): name = models.CharField(max_length=100) tagline = models.TextField() class Meta: abstract = True class BlogForm(forms.ModelForm): class Meta: model = Blog fields = ( '__all__' ) class MetaData(models.Model): # pub_date = models.DateField() # mod_date = models.DateField() n_pingbacks = models.CharField(max_length=255) rating = models.CharField(max_length=255) class Meta: abstract = True class MetaDataForm(forms.ModelForm): class Meta: model = MetaData fields = ( '__all__' ) class Author(models.Model): name = models.CharField(max_length=200) email = models.EmailField() def __str__(self): return self.name class AuthorForm(forms.ModelForm): class Meta: model = Author fields = ( 'name', 'email' ) class Entry(models.Model): blog = models.EmbeddedModelField( model_container=Blog, model_form_class=BlogForm ) meta_data = models.EmbeddedModelField( model_container=MetaData, model_form_class=MetaDataForm ) headline = models.CharField(max_length=255) body_text = models.TextField() authors = models.ArrayReferenceField( to=Author, on_delete=models.CASCADE, ) n_comments = models.CharField(max_length=255) def __str__(self): return self.headline But when I use django admin to create a new entry here is the error that I get: TypeError at /admin/app/entry/add/ int() argument must be a string, a bytes-like object or a number, not 'set' Request Method: POST Request URL: http://localhost:8000/admin/app/entry/add/ Django Version: 2.1.3 Exception Type: TypeError Exception Value: int() argument must be a string, a bytes-like … -
QuerySet.values('field_name') only returns id
I have a model named Comment that has another model Post as a foreign key. It also has a many to many relation with the user model. In [136]: user = User.get(pk=1) In [137]: all_comments = Comment.objects.all() In [138]: seen_comments = user.seen_comments.all() In [139]: unseen_comments = all_comments.difference(seen_comments) Here is the structure of the QuerySets: In [140]: all_comments Out[140]: <QuerySet [<Comment: Test comment>, <Comment: Test comment 2>, <Comment: Test comment 3>]> In [141]: all_comments.values() Out[141]: <QuerySet [{'id': 17, 'post_id': 44, 'text': 'Test comment', 'created_date': datetime.datetime(2018, 12, 18, 7, 0, tzinfo=<UTC>), 'user_id': 1}, {'id': 19, 'post_id': 44, 'text': 'Test comment 2', 'created_date': datetime.datetime(2018, 12, 19, 9, 0, tzinfo=<UTC>), 'user_id': 20}, {'id': 20, 'post_id': 44, 'text': 'Test comment 3', 'created_date': datetime.datetime(2018, 12, 27, 8, 12, 27, 338467, tzinfo=<UTC>), 'user_id': 1}]> The unseen_comments is a QuerySet of Comment objects. In [142]: unseen_comments Out[142]: <QuerySet [<Comment: Test comment>, <Comment: Test comment 3>]> In [143]: unseen_comments.values() Out[143]: <QuerySet [{'id': 17, 'post_id': 44, 'text': 'Test comment', 'created_date': datetime.datetime(2018, 12, 18, 7, 0, tzinfo=<UTC>), 'user_id': 1}, {'id': 20, 'post_id': 44, 'text': 'Test comment 2', 'created_date': datetime.datetime(2018, 12, 27, 8, 12, 27, 338467, tzinfo=<UTC>), 'user_id': 1}]> Now, if I try to get the id of all posts that are … -
Is there any way to create a web crawler using Python and Django (No Scrapy)
I need to create a web crawler using Python and Django where crawler should return all images where it crawled -
how to use yml files in python ChatterbotCorpusTrainer for a django application
I am building a chatbot using python chatterbot and want to host it using django. I have some yml files which are used to train the chatbot. In views.py, I can't link them. `chatbot = ChatBot( 'Ron Obvious', trainer='chatterbot.trainers.ChatterBotCorpusTrainer' ) chatbot.train("conversation") ` Here "conversation" is the yml file I want to use for training. It is also in the same folder. But Error is given as "NO such directory or file found". How to fix this issue? -
image: ["No file was submitted."] angular 6 ? tried DRF image and file field both
Here are my code for file uploading to s3. for now i am saving it in local class UploadedImage(models.Model): image = models.ImageField("Uploaded image", upload_to=scramble_uploaded_filename) thumbnail = models.ImageField("Thumbnail of uploaded image", blank=True) title = models.CharField("Title of the uploaded image", max_length=255, default="Unknown Picture") description = models.TextField("Description of the uploaded image", default="") def __str__(self): return self.title def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.thumbnail = create_thumbnail(self.image) super(UploadedImage, self).save(force_update=force_update) below is my serializers class UploadedImageSerializer(serializers.ModelSerializer): class Meta: model = UploadedImage fields = ('pk', 'image', 'thumbnail', 'title', 'description', ) read_only_fields = ('thumbnail',) and views class UploadedImagesViewSet(viewsets.ModelViewSet): queryset = UploadedImage.objects.all() serializer_class = UploadedImageSerializer this is working fine but i am getting error while integration api in angular 6. below code for angular 6 ts and html import { Component, OnInit } from '@angular/core'; import { HttpClient, HttpHeaders} from '@angular/common/http'; import { Router } from '@angular/router'; import { ViewChild } from '@angular/core'; @Component({ selector: 'app-photo-upload', templateUrl: './photo-upload.component.html', styleUrls: ['./photo-upload.component.css'] }) export class PhotoUploadComponent implements OnInit { @ViewChild("fileInput") fileInput; constructor(private http: HttpClient ,private router: Router) { } ngOnInit() { } url: string | ArrayBuffer; onSelectFile(event) { // called each time file input changes if (event.target.files && event.target.files.length>0) { console.log(event.target.files[0]); var reader = new FileReader(); reader.readAsDataURL(event.target.files[0]); // read file as … -
Graphql searches by foreign object name but not by foreign object id
This is filtering by id of topic. Graphql doesn't error, but it just do not filter by topic_id: class ArticleNode(DjangoObjectType): class Meta: model = Article filter_fields = ['topic__id'] interfaces = (relay.Node, ) oid = graphene.Field(graphene.Int) def resolve_oid(self, info, **kwargs): return self.id But when I filter by name of topics: class ArticleNode(DjangoObjectType): class Meta: model = Article filter_fields = ['topic__name'] interfaces = (relay.Node, ) oid = graphene.Field(graphene.Int) def resolve_oid(self, info, **kwargs): return self.id It works perfectly with name. However, I need to filter by id. Graphql query: { allArticles(topic_Name: "topic1") { edges { node { title topic { name } } } } } GraphQl query that doesn't error, but not works properly: { allArticles(topic_Id: 1) { edges { node { title topic { name } } } } }