Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Saving data to elasticsearch with django
How can I save nested-json data to Elasticsearch with Django? I want to take data from Twitter, enrich it and save it to elasticsearch but jsonfield etc. not accepting. charfield or another saved data as string-not dict -
Is there any way I can pass a filtered query set into Django's pagination?
view.py def quiz(request): question_topic = request.POST.getlist("topic_checkbox") # Retrieves list of topics selected by user question_list = Quiz.objects.filter(Topic_name__in = question_topic) #filters out questions by topics paginator = Paginator(question_list,1) # when i pass all the objects rather than the filtered query set it seems to work but when i paginate with the filtered queryset only the first page loads page = request.GET.get('page') try: question_list = paginator.page(page) except PageNotAnInteger: question_list = paginator.page(1) except EmptyPage: question_list = paginator.page(paginator.num_pages) return render(request,"Quiz/quiz_home.html",{"question_list":question_list}) quiz_home.html {% block content %} {% for q in question_list %} # loops through the filtered queryset {% if question_list.has_next %} <h3>Question {{q.id}}</h3> <form method="POST" action="?page={{ question_list.next_page_number }}">{% csrf_token %} # The form should enable me to gather the users input whilst simultaneoulsy going to the next question in the for loop. But when question sumbitted the next page is blank showing no contents {% if q.picture %} <img src="/media/{{q.picture}}"> <br> {% endif %} {{q.id}}.) </label><label id="question_text">{{q.question}}</label><br> <input type="hidden" id= "q_id" name="q_id" value="{{q.id}}"> <input type="hidden" id= "topic" name="topic" value="{{q.topic}}"> <input type="radio" id="opt1" name="options" value="{{q.option1}}" required>{{ q.option1 }}<br> <input type="radio" id="opt2" name="options" value="{{q.option2}}" required>{{ q.option2 }}<br> <input type="radio" id="opt3" name="options" value="{{q.option3}}" required>{{ q.option3 }}<br> <hr> <input type="submit" id="mybtn" value="Submit"> #once clicked it should paginate to … -
Pretty print django.db.models.JSONField in Django admin?
Django >= 3.1 supports a new JSONField model field. I am using one like this: from django.db import models class Example(models.Model): foobar = models.JSONField() I've also included this model in Django's admin section. However, the field is just a simple textarea with the JSON included, not pretty printed. How can I make sure the JSON displayed in Django's admin section is pretty printed, with indentation, like this: { "example": { "a": 1, "b": 2 } } -
ModuleNotFoundError: No module named 'cart.context_processors'
I am working on the django project by following the book. I am using Django version : 3.1.2.I added 'cart' app to the project. But when I worked with context_processor , I get the error.Can someone help me? I'm having this error: error screenshot This is "settings.py" # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'shop.apps.ShopConfig', 'cart.apps.CartConfig', ] ROOT_URLCONF = 'myshop.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'cart.context_processors.cart', ], }, }, ] WSGI_APPLICATION = 'myshop.wsgi.application' # Database # https://docs.djangoproject.com/en/3.1/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } CART_SESSION_ID = 'cart' STATIC_URL = '/static/' -
Django TypeError: 'Library' object is not callable
I'm upgrading code to the latest version of Django Version: 3.1.2 from django.template import Variable, Library register = Library() def striplinebreaks(value, arg): """ Removes all values of arg from the given string. """ safe = isinstance(value, SafeData) value = value.replace('\n', u'').replace('\r', u'').replace('\t', u'') if safe and arg != ';': return mark_safe(value) return value register('striplinebreaks') getting this error File "/home/sam/code/kpsga/lamusoftware/generic/templatetags/striplinebreaks.py", line 18, in <module> register(striplinebreaks) TypeError: 'Library' object is not callable -
why is django 'objects.filter' giving empty variable?
Please ignore the question cause i am newbie. :) my django views.py -- def search(request): if request.method == 'POST': try: query = request.POST["query"] try: query2 = User.objects.get(username=query) except: query2 = None if query2 == None: results = info.objects.filter(name=query) else: results = info.objects.filter(user=query2, name=query) return render(request, "search.html", {"results": results}) # https://docs.djangoproject.com/en/dev/topics/db/queries/# #spanning-multi-valued-relationships except: messages.info(request, "User not found") return redirect(home) else: pass my html -- {{results}} {% for result in results %} <a href="profile_seen?profile_seen={{result.user}}-1"> <div style="border: 0.7px solid gray;" class="row card"> <div style="display: flex;align-items: center; justify-content: center;"> <img style="width: 107px; margin: 10px 2%;" class="img-fluid" src="https://facyfun-bucket.s3.ap-south-1.amazonaws.com/{{result.profile_pic}}" alt="error"> <ul style="padding: 11px 12%;" class="list-group list-group-flush"> <li style="font-size: 32px;" class="list-group-item p-0">{{result.user}}</li> <li style="font-size: 19px;" class="list-group-item p-0">{{result.name}}</li> <li style="font-size: 17px;" class="list-group-item p-0">age {{result.age}}y</li> </ul> </div> </div> </a> {% endfor %} Error -- It always sends empty variable(results). But admin shows that it has value. Thanks Mam/Sir in Advance. -
Is updating a postgres database from an unsupported version important?
So far, I see only two reasons that make me consider an update from Postgres 9.4 (which is already an unsupported version). I want to use Django 3.1 for the development of a new web and this new version of Django does not support Postgres 9.4 anymore. I would have a new functionality and maybe an improved performance. Are there other, maybe more important reasons why to update? Should I care that it is an unsupported verion? And if yes, is it worth to update all the way to the newest stable version? -
Using curl with @login_required
I have a function: def foo(request): qs = Example.objects.all() for query in qs: query.param += 10 query.save(update_fields=['param']) return redirect('main:index') urlpatterns = path('foo/', foo) When i add @login_required the function stops executing with curl. I tried using .netrc, -u, --digest, but it still doesn't work. * Trying 127.0.0.1:8000... * TCP_NODELAY set * Connected to localhost (127.0.0.1) port 8000 (#0) * Server auth using Basic with user 'admin' > GET /foo/ HTTP/1.1 > Host: localhost:8000 > Authorization: Basic YwrtaW76Ttd0d4E7BWo= > User-Agent: curl/7.68.0 > Accept: */* > * Mark bundle as not supporting multiuse < HTTP/1.1 302 Found < Date: Mon, 26 Oct 2020 20:24:37 GMT < Server: WSGIServer/0.2 CPython/3.8.5 < Content-Type: text/html; charset=utf-8 < Location: /users/login/?next=/foo/ < X-Frame-Options: DENY < Content-Length: 0 < Vary: Cookie < X-Content-Type-Options: nosniff < Referrer-Policy: same-origin < * Connection #0 to host localhost left intact -
How to run django migrations with one command
I have an issue with Django migration. I have more than one database in my project. And I want to do the migration for all of them. I wrote my own migrations and if I run the commands below, everything works fine. python manage.py migrate app-name first_migration python manage.py migrate --datatbase=db_1 app-name first_migration python manage.py migrate --datatbase=db_2 app-name first_migration python manage.py migrate app-name second_migration python manage.py migrate --datatbase=db_1 app-name second_migration python manage.py migrate --datatbase=db_2 app-name second_migration python manage.py migrate app-name third_migration python manage.py migrate --datatbase=db_1 app-name third_migration python manage.py migrate --datatbase=db_2 app-name third_migration But I want to automate it, to run only: python manage.py migrate Unfortunately, when I do it I have the below error for migration3 django.db.utils.operationalerror no such column: column_name But column_name was added in migration2 Have anybody any idea, how can I resolve this issue and run all migration with one command? -
Django/Heroku AJAX Request Doesn't Seem To Execute
I am needing to save the contents of a javascript variable in the main page of my site (index.html), to the database that my heroku/django app is connected to. I found a related post here but my AJAX request to send a variable from JavaScript to then access in python is not running. Javascript/HTML and AJAX in index.html: <button type="button" id="send-my-url-to-django-button">Send URL to Django View</button> <script type="text/javascript"> $(document).ready(function() { var url = data.result.docs[i].source.enriched.url.url; alert("ok"); $("#send-my-url-to-django-button").click(function() { $.ajax({ url: "/process_url_from_client", type: "POST", dataType: "json", data: { url: url, csrfmiddlewaretoken: '{{ csrf_token }}' }, success : function(json) { alert("Successfully sent the URL to Django"); }, error : function(xhr,errmsg,err) { alert("Could not send URL to Django. Error: " + xhr.status + ": " + xhr.responseText); } return false; }); }); }); </script> relevant lines from urls.py url(r'^process_url_from_client/$', hello.views.process_url_from_client, name='process_url_from_client'), relevant lines from views.py def process_url_from_client(request): url = request.POST.get('url') save = SaveFile(data=str(url)); save.save(); This is supposed to send the URL from index.html to then be accessed in views.py and saved to the database. However clicking the button does not seem to execute the AJAX script at all. I don't get a success or error message. Any ideas why this isn't working? Any help would … -
topics = Topic.objects.filter(owner=request.user).order_by('date_added') Not working
I'm a beginner in Django and I'm using a book called Python Crash Course to guide me. I am currently doing the app development project and I'm running into some errors. Apparently, the error is caused by this line: topics = Topic.objects.filter(owner=request.user).order_by('date_added'). Here is my full code for views.py: from django.shortcuts import render from django.http import HttpResponseRedirect, Http404 from django.http import HttpResponseRedirect from django.urls import reverse from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm def index(request): return render(request, 'learning_logs/index.html') @login_required def topics(request): topics = Topic.objects.filter(owner=request.user).order_by('date_added') context = {'topics': topics} return render(request, 'learning_logs/topics.html', context) @login_required def topic(request, topic_id): topic = Topic.objects.get(id=topic_id) if topic.owner != request.user: raise Http404 entries = topic.entry_set.order_by('-date_added') context = {'topic': topic, 'entries': entries} return render(request, 'learning_logs/topic.html', context) @login_required def new_topic(request): if request.method != 'POST': form = TopicForm() else: form = TopicForm(data=request.POST) if form.is_valid(): new_topic = form.save(commit=False) new_topic.owner = request.user new_topic.save() form.save() return HttpResponseRedirect(reverse('learning_logs:topics')) context = {'form': form} return render(request, 'learning_logs/new_topic.html', context) @login_required def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) if request.method != 'POST': form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return HttpResponseRedirect(reverse('learning_logs:topic', args=[topic_id])) context = {'topic': topic, 'form': form} return render(request, 'learning_logs/new_entry.html', context) @login_required … -
Reading Froms.py code from Model data in django
I have a some class in forms.py and I want reading code by user entry in specific model for example This code need read from model user entry class SearchForm(BSQuickSearchForm): def layout(self): self.helper.layout = Layout( 'q_quick_search_kw', StrictButton('Search', type="submit", css_class='btn-sm btn-default'), StrictButton('Export', type="submit", name="export", css_class='btn-sm btn-default'), ) -
Comment is not displaying in django after submission
I have tried to submit a comment from app rather than django admin. Comment is not displaying when submitted from my created app. But it is displaying when I add a comment from django admin app. May be I am doing something wrong in views.py file. Can anyone help me on this? Thank you. views.py: @login_required def book_review(request,id): book = get_object_or_404(Bookslist, id=id) comment=Comment.objects.all().filter(post_id=id) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.user_id = request.user post.message= comment post.save() return redirect('book_review', id=id) else: form=CommentForm() return render(request, "books/book_review.html", {'book':book, 'comment':comment, 'form': form}) models.py: class Comment(models.Model): message= models.TextField('Message',null=True) date_comment=models.DateTimeField(default=now, null=True) user_id= models.ForeignKey(User, on_delete=models.CASCADE,null=True) post_id=models.ForeignKey(Bookslist,on_delete=models.CASCADE,null=True) forms.py: from django import forms from .models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['message', ] book_review.html: {% extends 'books/base.html' %} {% load static %} {% block stylesheet %} <link rel="stylesheet" href="{% static 'accounts/accounts.css' %}"> {% endblock %} {% block content %} <div class = "container"> <ul class = "nav nav-tabs" id = "myTab" role = "tablist"> <li class = "nav-item"> <a class = "nav-link active" id = "summary-tab" data-toggle = "tab" href = "#summary" role = "tab" aria-controls = "summary" aria-selected = "true">Summary</a> </li> <li class = "nav-item"> <a class = … -
Django Python Autocomplete Light select dont show
I have a problem adding the autocomplete light select2 on my custom Model. I got the package installed with pip, and added in settings.py: INSTALLED_APPS = [ 'dal', 'dal_select2', 'dal_legacy_static', 'django.contrib.admin', 'django.contrib.auth', .... My url for get the querysets: url(r'^property-autocomplete/$', PropertyAutocomplete.as_view(),name='property-autocomplete'), I tested it and I get the results correctly. My autocomplete: class PropertyAutocomplete(autocomplete.Select2QuerySetView): def get_queryset(self): qs = Property.objects.all() if self.q: qs = qs.filter(p_address_street=self.q) return qs And on my form, I added: class ReserveForm(BSModalModelForm): re_renter = forms.ModelChoiceField(queryset=User.objects.filter(u_user_type=0).order_by('-pk')) re_inquilinos = forms.ModelMultipleChoiceField(queryset=User.objects.filter(u_user_type=0).order_by('-pk'), required=False) re_enter_date = forms.DateField(required=True, widget=forms.TextInput(attrs={'type':'date'})) re_exit_date = forms.DateField(required=True, widget=forms.TextInput(attrs={'type':'date'})) re_property = forms.ModelChoiceField(queryset=Property.objects.all(), widget=autocomplete.ModelSelect2(url='property-autocomplete')) The re_property is the field I want to be selectable, is a Foreign Key value. In my HTML form I got: {% load crispy_forms_tags %} {% load static %} <form method="POST" action=""> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title">Modificar/Crear Reserva</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.re_property|as_crispy_field }} </div> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> <button type="button" class="submit-btn btn btn-primary">Create</button> </div> </form> {{form.media}} I tried to import select2.js, jquery, etc, But nothing work. The actual result is like a normal select: And I only have that register to choose. I don't know … -
Schema creation and migrations from Django Admin UI
I was searching about the specific need, but did not got many useful results, so i will just ask for any ideas, libraries, hints that you may have. So the idea I want to realize comes from a model that is totally unrelated to the Django app and it may change over time, based on some requirement changes. So i do not want the user to manually execute some SQL commands when changes occur, and i want him to do that over the Admin UI where he would edit some existing columns, constraints, add new ones, using the standard inputs that an admin gives (check boxes, selects etc). From the input he makes, the tables will be created (first time), altered after any change after it etc. So the schema he would work on would look something like this: Table -------------------------------- | id | table_name | table_type | -------------------------------- | 1 | table1 | type1 | -------------------------------- | 2 | table2 | type2 | -------------------------------- Column ----------------------------------------------------------------- | id | column_name | nullable | unique | primary_key | table_id | ----------------------------------------------------------------- | 1 | column1 | false | true | true | 1 | ----------------------------------------------------------------- | 2 | column2 | … -
Django contrib comments: RuntimeError: Model class django_comments.models... application in INSTALLED_APPS
I'm trying to add django-contrib-comments Version: 1.9.2 and Django Version: 3.1.2 I've added it to settings INSTALLED_APPS INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ... #imports 'comments_moderation', ] it throws this error File "/home/sam/code/kpsga/lamusoftware/blog/models.py", line 5, in <module> from django_comments.moderation import moderator File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/moderation.py", line 369, in <module> moderator = Moderator() File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/moderation.py", line 294, in __init__ self.connect() File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/moderation.py", line 302, in connect signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=django_comments.get_model()) File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/__init__.py", line 49, in get_model from django_comments.models import Comment File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django_comments/models.py", line 12, in <module> class Comment(CommentAbstractModel): File "/home/sam/code/envs/kpsga/lib/python3.8/site-packages/django/db/models/base.py", line 113, in __new__ raise RuntimeError( RuntimeError: Model class django_comments.models.Comment doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS. which suggests it needs to be added to INSTALLED_APPS but it's already added. -
How to use wkHTMLtoPDF running in docker-compose in Django application
I have a problem with undestanding on how to use wkHTMltoPDF, that I run in docker-compose and Django. Also I can't understand how to setup it in Django and use it in the right way. I will be very glad for any help. My docker-compose.yml: version: '3.7' services: db: image: postgres:13.0 restart: always environment: POSTGRES_PASSWORD: trytofindme ports: - 15432:5432 adminer: image: adminer restart: always ports: - 8020:8080 wkhtmltopdf: image: openlabs/docker-wkhtmltopdf-aas:latest volumes: - .:/data So, I can't even imagine where I should do it in Django. The example of usage that I need: on main page I fill some forms and then click button "Generate". It should send async requests on generating pdf file of this page with filled forms. Can anybody help me to realise it? -
Django Latest Timestamped Items from Many
I have a Model where there can be multiple instances of the same entry. They have their respective timestamps as I scrape the same data sources daily. I want to only receive the latest entries for each item. I wanted to approach this as grouping by the identifier of the items, which will result in groups of the same items but different timestamps, then get the latest from each group and combine this. My question is, how can this be done in Django? From what I have read I can use the "annotate()" function to GroupBy and then use "latest()" on each group. Is there any better way of accomplishing the same result or is this a proper approach? Thank you! -
Django uploaded file doesn't process
I'm building a Django web-app where the user needs to upload a file. This file should go through a machine-learning alogritme after that the results will be presented on a different page. right now it works if I have text fields present for every feature but when I want to upload a csv file(the csv file is called test.csv) put it in a pandas dataframe the resultpage doesn't show and it looks like the csv file isn't processed. what it should do is if file is uploaded keep the uploaded file in memory process it and return the output on the results page. HTML {% extends "base.html" %} {% block content %} <div class="content"> <div class="row"> <div class="col-lg-4"> <div class="card card-tasks"> <h1> </h1> <form action="{% url 'result' %}"> {% csrf_token %} <p>temp_normal:</p> <input class="form-control" type="text" name="temp_normal"> <br> <p>hour:</p> <input class="form-control" type="text" name="hour"> <br> <p>hour_x:</p> <input class="form-control" type="text" name="hour_x"> <br> <p>hour_y:</p> <input class="form-control" type="text" name="hour_y"> <br> <input class="form-control" type="submit" value='Submit'> </form> </div> </div> <div class="col-lg-4"> <div class="card card-tasks"> <form action="{% url "result" %}" method="POST" enctype="multipart/form-data" class="form-horizontal"> {% csrf_token %} <div class="form-group"> <label for="name" class="col-md-3 col-sm-3 col-xs-12 control-label">File: </label> <div class="col-md-8"> <input type="file" name="csv_file" id="csv_file" required="True" class="form-control"> </div> </div> <div class="form-group"> <div … -
When I clicked on 'viewall' submit button on html it goes to 'RestInfo url' and show NoReverseMatch at error Django
Template Code <a href="{% url 'ViewAll' cust.custId %}" <button class="btn cart viewall">View All</button></a> <a href="{% url 'RestInfo' rest.restId cust.custId %}" style="color: #000000;">RestInfo</button></a> url.py path('ViewAll/<str:mycid>',views.ViewAll,name='ViewAll') path('myRest/<int:myid>/<str:cid>',views.RestInfo,name='RestInfo'), views.py def ViewAll(request,mycid): print("Welcome",mycid) rests= Restaurant.objects.all() return render(request,'viewall.html',{'rests':rests}) def RestInfo(request,myid=None,cid=None): rests= Restaurant.objects.filter(restId=myid) return render(request,"restInfo.html",{'rest':rests[0]}) When I Clicked on button in which viewll url is given then it goes to restinfo and shows me noreversematch error -
Permissions Issues Linux
I'm trying to follow the Django official tutorial. When I'm trying to create a new project: django-admin startproject mysite I have this error : CommandError: [Errno 13] Permission denied: '/home/olivier/Documents/python/Django/official_tutorial/mysite' I thought that I didn't have the rights in this folder. Which is weird cause it's my personal folder. So I checked with ls -l /home : total 4 drwxrwxr-x 27 olivier olivier 4096 oct. 22 15:16 olivier Apparently I do have the rights. Side note I cannot create a venv in it with virtualenv venv virtualenv: error: argument dest: the destination . is not write-able at /home/olivier/Documents/python/Django/official_tutorial SystemExit: 2 What seems to be the problem here ? I'm running Pop!_OS 20.04 LTS -
Filtering Objects Using Other Objects - Queryset, Django
In my Django application, the user provides a unique product name which matches field of another object and then displays second object on the list (that the user sees). So the object's display condition looks something like this obj1.name == obj2.name It is extremely simple for one object but how to use it for get queryset (where the field of objects 1 is equal to the field of object 2)? An example of the effect I want to get: Obj1.objects.all() = ('AS2', 'AS9', 'AD5', 'AG1') Obj2.objects.all() = ('DD1', 'AS2', 'AS9', 'AP33', 'AD5', 'AG1', 'KQ1', 'LG4') query1 = Obj1.objects.all() query2 = obj2.objects.filter(name=???) #and query2 return all objects product which name=name well ('AS2', 'AS9', 'AD5', 'AG1') but from Obj2 -
django isn't sending data to html?
I am a newbie so please ignore the question quality :). my django views.py -- def search(request): if request.method == 'POST': try: query = request.POST["query"] try: query2 = User.objects.get(username=query) except: query2 = None if query2 == None: results = info.objects.filter(name=query) else: results = info.objects.filter(user=query2, name=query) if results == "": results=None return render(request, "search.html", {"results": results}) # https://docs.djangoproject.com/en/dev/topics/db/queries/# #spanning-multi-valued-relationships except: messages.info(request, "User not found") return redirect(home) else: pass my html page -- <div class="container"> {% for result in results %} <a href="profile_seen?profile_seen={{result.user}}-1"> <div style="border: 0.7px solid gray;" class="row card"> <div style="display: flex;align-items: center; justify-content: center;"> <img style="width: 107px; margin: 10px 2%;" class="img-fluid" src="https://facyfun-bucket.s3.ap-south-1.amazonaws.com/{{result.profile_pic}}" alt="error"> <ul style="padding: 11px 12%;" class="list-group list-group-flush"> <li style="font-size: 32px;" class="list-group-item p-0">{{result.user}}</li> <li style="font-size: 19px;" class="list-group-item p-0">{{result.name}}</li> <li style="font-size: 17px;" class="list-group-item p-0">age {{result.age}}y</li> </ul> </div> </div> </a> {% endfor %} Error -- I am sending data(results) but it still shows nothing(not even null value). -
Django save nested data to Elasticsearch
I want to save nested data to elastic, I created model, document and serialize. Incoming Data(from twitter and parsed): {'created_at': '2020-10-26 20:00:14', 'tweetID': xxx, 'userID': xxx, 'userName': 'xxx', 'userScreenName': 'xxx', 'full_text': 'xxx', 'hashtag': ['xxx'], 'urls': ['xxx'], 'ioc': [ {'type': 'xxx', 'value': 'yyy', 'first_discovery': '2020-10-26 20:00:14', 'last_observed': '2020-10-26 20:00:14'}, {'type': 'kkk', 'value': 'mmm', 'first_discovery': '2020-10-26 20:00:14', 'last_observed': '2020-10-26 20:00:14'}]} My Model class: from django.db import models from django.utils.translation import ugettext_lazy as _ class TwitterPost(models.Model): created_at = models.DateTimeField( _('created_at'), blank=True, null=True, ) tweetID = models.CharField( _('tweetID'), blank=True, null=True, default=None, max_length=100, ) userID = models.CharField( _('userID'), null=True, blank=True, default=None, max_length=100, ) userName = models.CharField( _('userName'), null=True, blank=True, default=None, max_length=200, ) userScreenName = models.CharField( _('userScreenName'), null=True, blank=True, default=None, max_length=200, ) full_text=models.CharField( _('full_text'), null=True, blank=True, default=None, max_length=500, ) hashtag = models.CharField( _('hashtag'), null=True, blank=True, default=None, max_length=250, ) urls = models.CharField( _('urls'), null=True, blank=True, default=None, max_length=200, ) hashtag = models.CharField( _('hashtag'), null=True, blank=True, default=None, max_length=250, ) urls = models.CharField( _('urls'), null=True, blank=True, default=None, max_length=200, ) def __str__(self): return self.tweetID class TwitterPostIOCs(models.Model): ioc = models.ForeignKey(TwitterPost, related_name='tweetIOC', on_delete=models.CASCADE) type = models.CharField( _('type'), null=True, blank=True, default=None, max_length=100, ) value = models.CharField( _('value'), null=True, blank=True, default=None, max_length=100, ) first_discovery = models.DateTimeField( _('first_discovery'), blank=True, null=True, ) last_observed = models.DateTimeField( _('last_observed'), blank=True, … -
Django: More pythonic way of saving form data to existing model
I'm currently saving my new ModelForm values by iteration of each form's cleaned values after validation. Is there a better way of doing this? Note: 'Activity' model already contains data for given example record_form = AddRecordTimeFrame(request.POST) activity_form = EditRecordGeneral(request.POST) activity_form_2 = EditRecordChassisDynoTest2(request.POST) if all([activity_form.is_valid(), activity_form_2.is_valid(), record_form.is_valid()]): test_record = RecordModel.objects.get(id=1) activity_record = test_record.activity for field, value in record_form.cleaned_data.items(): setattr(test_record, field, value) for field, value in activity_form_2.cleaned_data.items(): setattr(activity_record, field, value) for field, value in activity_form.cleaned_data.items(): setattr(activity_record, field, value) I'd like to make use of the form's .save() but only change values of the model that are in the fields of the modelform.