Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Math calculations - backend or frontend
I am creating a web application(Django + Angular) whose main purpose is to draw shapes. I calculate and draw all the shapes myself. Where is it better to do the calculations (calculating line equations, finding common points)- on the backend and ask the server or on the frontend? Thanks -
Efficiently serializing multiple objects that need to make REST call
Say I have a simple model, Account, as follows: class Account(models.Model): name = models.CharField(db_index=True) And an AccountSerializer as follows: class AccountSerializer(serializers.ModelSerializer): name = CharField(source="account.name") def _get_favorite_color(self, obj: Account): # Make a rest call to get this account's favorite color favorite_color = _get_favorite_color(name) I also have a ViewSet with a list action to get all accounts, as well as a Serializer to serialize each items. The JSON returned has the following shape: { 'accounts':[ {'name':'dave', 'favorite_color':'blue'}, {'name':'john', 'favorite_color':'black'}, ] } What is the django-esque way of 'bulk' fetching these favorite colors? This REST call to obtain favorite colors can take as an input a list of all account ids and return them in a single list, avoiding to make n REST calls when just one can do. Where would this logic live to make the most sense? I can't put this logic in the Serializer considering that it only handles one object at a time. Is there another place to put it rather than the ViewSet? My understanding is that ViewSets should be as lean as possible. -
Django Rest API - How to change user password?
I'm trying to change my users password using Django REST Framework (DRF) but I only get back a empty response and I don't understand why, please have a look at my code. url.py re_path(r'^api/v1/user/change_password$', API_Views.change_password, name='api_change_password'), views.py @api_view(['PUT']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def change_password(request,): if request.method == 'PUT': serializer = ChangePasswordSerializer(request.user) return JsonResponse(serializer.data, safe=False) serializers.py class ChangePasswordSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) old_password = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('old_password', 'password', 'password2') def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError({"password": "Password fields didn't match."}) return attrs def validate_old_password(self, value): user = self.context['request'].user if not user.check_password(value): raise serializers.ValidationError({"old_password": "Old password is not correct"}) return value def update(self, instance, validated_data): instance.set_password(validated_data['password']) instance.save() return instance What do I miss here? Please also have a look at the request I build -
django attachments broke when check for authentcation
i have media folder contain attachments, this attachments can be exported to other intgerations like JiRA, it works well without authentcation , but with auth check the files are broken not sure why -
Django Login with Captcha and two factor auth
I'm quite new to Django and have managed to create my own login page integrated with axes and repatcha which basically displays captcha upon 3 failed login attempts with my own error messages - this all works fine as required howver I would now also like to add two factor authentication with what I already have implemented. I had have managed to install django two factor auth package but it seems I am forced to use the login page that comes with two factor auth package. Having spent so much time on my own login and with added features I desperately need to keep this in place. I believe I am able to edit the two factor auth template files but the main issue is being able to use the features from my existing view/decorators with the two factor auth views. The following is my current setup: URLS from django.urls import path, include from . import views urlpatterns = [ path('login/', views.loginpage, name="login"), path('logout/', views.logoutuser, name="logout"), ..., ] View @axes_dispatch @check_recaptcha_login def loginpage(request, credentials: dict = None): attempts_list = get_user_attempts(request, credentials) attempt_count = max( ( attempts.aggregate(Sum("failures_since_start"))[ "failures_since_start__sum" ] or 0 ) for attempts in attempts_list ) #print(attempt_count) attempt_count = attempt_count … -
Django extending template
When I extend the home.html file with {% extends 'menu.html'%}, it also extends it with the menu.css file. I need a home.css file. How can I fix this problem? Thank you for your help -
How to connect the addresses in my sqlite db to position markers with google maps API's Django
I'm starting to program in Django and also starting to use Google API's, in a few words for my little project, i need to set marker points based in my SQLite db linked to the addresses the users register, to the map displayed in my HTML, i know that i need to convert those addresses strings into coordinates in a JSON file, and that JSON file is the one the API can read and display, so far i managed to set the map, geolocation and set pointers from an example file based on a url which google documentation gives you. I'll be forever grateful if someone can guide me tru these questions: a) How do i convert that address variables of my model in Django to a readable Google API JSON. b) How do i call that JSON file to display it on my map. Thank you so much for your time! let map; function initMap() { map = new google.maps.Map(document.getElementById("map"), { zoom: 2, center: new google.maps.LatLng(2.8, -187.3), mapTypeId: "terrain", }); infoWindow = new google.maps.InfoWindow(); const locationButton = document.createElement("button"); locationButton.textContent = " Mi ubicacion "; locationButton.classList.add("custom-map-control-button"); map.controls[google.maps.ControlPosition.TOP_CENTER].push(locationButton); locationButton.addEventListener("click", () => { // Try HTML5 geolocation. if (navigator.geolocation) { navigator.geolocation.getCurrentPosition( (position) … -
TypeError: __init__() got an unexpected keyword argument 'widgets'
i am getting error when i write forms.py from django.contrib.auth.forms import AuthenticationForm, UserCreationForm, UsernameField class SignupForm(UserCreationForm): password1= forms.CharField(label='password',widget=forms.PasswordInput(attrs={'class':'form-control'})) password2= forms.CharField(label='Confirm password(again)',widget=forms.PasswordInput(attrs={'class':'form-control'})) the server says username= UsernameField(label='username',widgets=forms.TextInput(attrs={'autofocus':True,'class':'form-control bg-success'})) File "C:\Users\ITS\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\fields.py", line 216, in __init__ super().__init__(**kwargs) TypeError: __init__() got an unexpected keyword argument 'widgets' but when i write widgets in meta class class LoginForm(AuthenticationForm): username= UsernameField(label='username') password= forms.CharField(label=('password'),strip=False) class Meta: widgets={ 'username':forms.TextInput(attrs={'autofocus':True,'class':'form-control'}), 'password':forms.PasswordInput(attrs={'autocomplete':'current-password','class':'form-control'}), } the server totally works but form control class doesn't in the html page. html code is here {% extends 'base.html' %} {% block content %} <div class="col-sm-10"> <h3 class="text-white my-5"> Login Page</h3> <form action="" method="post" novalidate> {% csrf_token %} {% for fm in form %} <div class=""> {{fm.label_tag}}{{fm}}<small class="text-warning">{{fm.errors| striptags}}</small> </div> {% endfor %}<br> <input type="submit" class=" btn btn-primary" value="Login"> {% if form.non_field_errors %} {% for error in form.non_field_errors %}<br> <p class="alert alert-danger my-3">{{ error}}</p> {% endfor %} {% endif %} </form> </div> {% endblock %} help me with this please.and thanks in advance. -
ValueError: Field 'maca' expected a number but got ''
I have a model like this class MacaModel(models.Model): maca = models.PositiveIntegerField( db_column='Maca', blank=True, null=True ) I have form like this class MacaForm(models.ModelForm): maca = forms.CharField(required=False,widget=forms.TextInput(attrs={'placeholder': 'Maca'})) I'm trying to send null value from input, but got this error ValueError: Field 'maca' expected a number but got ''. How can I handle if I don't send a value accept is as a None value or something like that? -
Django DRF - Unable to change user password as user at request is None
my application has an endpoint to change a users password using Django rest framework (DRF). I'm currently running into the following error if I try to change a users password: File "/App/App_API/serializers.py", line 32, in validate_old_password if not user.check_password(value): AttributeError: 'NoneType' object has no attribute 'check_password' [1 urls.py re_path(r'^api/v1/user/change_password$', API_Views.change_password, name='api_change_password'), views.py @api_view(['GET', 'POST']) @authentication_classes([JSONWebTokenAuthentication]) @permission_classes([IsAuthenticated]) def change_password(request): if request.method == 'POST': serializer = ChangePasswordSerializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.save() # if using drf auth_token, create a new token if hasattr(user, 'auth_token'): user.auth_token.delete() token, created = Token.objects.get_or_create(user=user) # return new token return Response({'token': token.key}, status=status.HTTP_200_OK) serializers.py class ChangePasswordSerializer(serializers.Serializer): old_password = serializers.CharField(max_length=128, write_only=True, required=True) new_password1 = serializers.CharField(max_length=128, write_only=True, required=True) new_password2 = serializers.CharField(max_length=128, write_only=True, required=True) def validate_old_password(self, value): user = None request = self.context.get("request") if request and hasattr(request, "user"): user = request.user if not user.check_password(value): raise serializers.ValidationError( _('Your old password was entered incorrectly. Please enter it again.') ) return value def validate(self, data): if data['new_password1'] != data['new_password2']: raise serializers.ValidationError({'new_password2': _("The two password fields didn't match.")}) password_validation.validate_password(data['new_password1'], self.context['request'].user) return data def save(self, **kwargs): password = self.validated_data['new_password1'] user = self.context['request'].user user.set_password(password) user.save() return user To me it seems that the user object within the serialize is simply = None. That again results into the question … -
Django3: Content of child template doesn't load
The posts object is loaded in view post_list using the custom manager defined inside models.py. list.html is trying to display the posts in base.html by iterating over the posts object. But the content of list.html is not rendered inside base.html Relevant screenshot added. base.html {% load static %} <!DOCTYPE html> <html> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static "css/blog.css" %}" rel="stylesheet"> </head> <body> <div id="content"> {% block content %} {% endblock %} </div> <div id="sidebar"> <h2>My blog</h2> <p>This is my blog.</p> </div> </body> </html> list.html {% extends "blog/base.html" %} {% block title %}My Blog{% endblock %} {% block content %} <h1>My Blog</h1> {% for post in posts %} <h2> <a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|truncatewords:30|linebreaks }} {% endfor %} {% endblock %} model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse class PublishedManager(models.Manager): def get_queryset(self): return super().get_queryset().filter(status='published') # Create your models here. class Post(models.Model): STATUS_CHOICES = ( ('draft', 'Draft'), ('published', 'Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) … -
how can i resolve ValueError: Field 'cid' expected a number but got ''.?
while performing migration I am getting this error... (env) PS C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter> python manage.py migrate Operations to perform: Apply all migrations: Recruiter, admin, auth, contenttypes, sessions Running migrations: Applying Recruiter.0003_auto_20211009_2038...Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\models\fields\__init__.py", line 1823, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: '' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 22, in <module> main() File "C:\Users\ashwi\Documents\GitHub\AMCH\AMCH_Recruiter\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\core\management\commands\migrate.py", line 244, in handle post_migrate_state = executor.migrate( File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\executor.py", line 227, in apply_migration state = migration.apply(state, schema_editor) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\migration.py", line 126, in apply operation.database_forwards(self.app_label, schema_editor, old_state, project_state) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\migrations\operations\fields.py", line 104, in database_forwards schema_editor.add_field( File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 330, in add_field self._remake_table(model, create_field=field) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\sqlite3\schema.py", line 191, in _remake_table self.effective_default(create_field) File "C:\Users\ashwi\Documents\GitHub\AMCH\env\lib\site-packages\django\db\backends\base\schema.py", … -
django foorloop counter restarts in a new page
currently I'm writing a simple todolist with django. I have a view and html file for showing the list of items, and I want a number for each task in the table starting from 1. I'm using {% footloop.counter %} for that in my template. Everything was ok until I wrote the paginator. when you choose to go to the next page, the counter starts from 1 again ,therefor the numbers in the table in each page start from one too. but I want the numbers to be continued in order until the last page. Is there any template tags or code snippets for that? Thanks in advance. here are the codes involved: **list.html:** {% for task in tasks %} <tbody> <tr> <th scope="row" class="col-md-1">{{ forloop.counter }}</th> <td class="col-md-2">{{ task.title }}</td> <td class="col-md-3">{{ task.description|truncatewords:10 }}</td> <td class="col-md-2">{{ task.time|date:"H:i" }} - {{ task.time|date:"D d M , Y" }}</td> </tr> </tbody> {% endfor %} <!--Pagination--> {% if is_paginated %} <div class="container p-4"> <div class="pagination justify-content-center"> <span class="step-links"> {% if page_obj.has_previous %} <a href="{% url 'home:list' 1 %}">&laquo; first</a> <a href="{% url 'home:list' page_obj.previous_page_number %}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{page_obj.paginator.num_pages }} </span> {% if page_obj.has_next %} <a … -
Django refreshing records at template only after re-running server
I've just started learning Django and I making my first App. I'm having that weird problem when i adding record to database, it actually adding it there but it won't show them at my page until i reload server by following command python manage.py runserver views.py def createStudent(request): form = StudentForm() if request.method == "POST": form = StudentForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("homePage") context = {"form": form} return render(request, "pages/addStudent.html", context) models.py class Students(models.Model): name = models.CharField(max_length=200) surname = models.CharField(max_length=200) card_id = models.IntegerField() unique_id = models.UUIDField( default=uuid.uuid4, unique=True, primary_key=True, editable=False) student_image = models.ImageField(null=True, blank=True, default="default_student.jpg") class Meta: verbose_name_plural = 'Students' #Methods def __str__(self): return f'{self.name} {self.surname}' addStudent.html {% extends "main.html" %} {% block addStudent %} <form method="POST" enctype="multipart/form-data"> {% csrf_token %} {{form.as_p}} <input type="submit"/> </form> {% endblock addStudent %} I think that bug appeared after I've started working with static files and added student_image = models.ImageField(null=True, blank=True, default="default_student.jpg") Have anyone faced that problem before? -
Building a Webscraping web-app using Django and Selenium
I am building a webscraping application(or tool) using django and Selenium. I've completed the webscraping part using selenium library in Python. I am wondering how I should convert that into a webapplication, that takes input from user, and scrape accordingly. If you've some links that I can go through I am willing to do that. Any guidance is great help! -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__main_doctor.email
i was trying to change null = False and Unique = True in EmailField and after it started giving me this error: django.db.utils.IntegrityError: UNIQUE constraint failed: new__main_doctor.email I have run the commands makemigrations and migrate but it still giving me this error. I tried undo these and then run commands but it still giving me error. here is my models.py file from django.db import models from phonenumber_field.modelfields import PhoneNumberField import os # Create your models here. import datetime def get_file_path(request, filename): filename_original = filename nowTime = datetime.datetime.now().strftime('%Y%m%d%H:%M:%S') filename = "%s%s" % (nowTime, filename_original) return os.path.join('uploads/', filename) class Doctor(models.Model): name = models.CharField(max_length=20) phone_number = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(null=False, unique=True, max_length=100) city = models.CharField(max_length=100) speciality = models.CharField(max_length=50) doc_image = models.ImageField(upload_to = get_file_path ,null = False, blank = False) kycdocument = models.ImageField(upload_to = get_file_path, null = False, blank = False) class Department(models.Model): dept_name = models.CharField(max_length=20) dept_Email = models.EmailField(max_length=100) dept_password = models.CharField(max_length=200) here is forms.py file from django import forms from .models import Doctor,Department class Doctorslist(forms.ModelForm): class Meta: model = Doctor fields = ('name','phone_number','email', 'city', 'speciality', 'doc_image', 'kycdocument') # widgets = { # 'name': forms.TextInput(attrs = {'class': 'form-control'}), # 'email': forms.EmailInput(attrs={'class': 'form-control'}), # 'city': forms.CharField(attrs={'class': 'form-control'}), # 'speciality': forms.CharField(attrs={'class': 'form-control'}), # } … -
How to pass a file uploaded to another view (next page) for further processing
I am working on a django app where I take an upload of a CSV file however once uploaded I want to simply display columns in another page of that CSV. Is there anyway to do this? something like def index(request): file = request.POST.get('file') redirect('nextpage', file) -
Django Model Struct within a Struct?
I'm trying to create a structure within a structure under Django's models.py. I know how to do this in C but am new to python. For example, I have a class: class OneDay(models.Model) hour1 = ? hour2 = ? ... hour23 = ? hour24 = ? Each hour will have a list of identical properties. I want to apply these properties to every single hour within the OneDay class. I don't believe they are ForeignKeys. class PeriodProperties(models.Model) isX = boolean isY = boolean isZ = boolean R = number P = number So with this I would be able to look up: hour5.isX == false? hour10.R > 50%? Something like that. Can anyone point me in the right direction? Thank you. -
Nginx and uWSGI behind AWS application load balancer with HTTPs
I'm having trouble getting my Django project with an Application Load Balancer ->Nginx -> uWSGI working in AWS. When I do the deployment without the Application Load Balancer everything is working just fine my Nginx is returning at port 443 and no errors but when used with the load balancer the error 504 and 502 happens. At etc/nginx/sites-available/ i have created my django_vps.conf upstream django { server unix:///home/ubuntu/Django_project/mysite.sock; } #redirecting http para https server{ listen 80; server_name servername.com; return 301 https://$host$request_uri; } server { listen 443 ssl http2; server_name servername.com; charset utf-8; #ssl configuration ssl_certificate /etc/ssl/ssl.pem; ssl_certificate_key /etc/ssl/ssl.key; client_max_body_size 75M; #Configurando TLSv1.3 protocol apenas ssl_protocols TLSv1.3; location /media { alias /home/ubuntu/Django_project/media; } location /static { alias /home/ubuntu/Django_project/static; } location / { uwsgi_pass django; include /home/ubuntu/Django_project/uwsgi_params; } } My uWSGI Params ( uwsgi_params ) uwsgi_param QUERY_STRING $query_string; uwsgi_param REQUEST_METHOD $request_method; uwsgi_param CONTENT_TYPE $content_type; uwsgi_param CONTENT_LENGTH $content_length; uwsgi_param REQUEST_URI $request_uri; uwsgi_param PATH_INFO $document_uri; uwsgi_param DOCUMENT_ROOT $document_root; uwsgi_param SERVER_PROTOCOL $server_protocol; uwsgi_param REQUEST_SCHEME $scheme; uwsgi_param HTTPS $https if_not_empty; uwsgi_param REMOTE_ADDR $remote_addr; uwsgi_param REMOTE_PORT $remote_port; uwsgi_param SERVER_PORT $server_port; uwsgi_param SERVER_NAME $server_name; My uwsgi.ini [uwsgi] chdir = /home/ubuntu/Django_project module = Django_project.wsgi home = /home/ubuntu/venv master = true processes = 10 socket = /home/ubuntu/Django_project/mysite.sock vacuum = true … -
Size of file stored on the s3 bucket
I have following model class MediaFile(Media): s3_file = GenericFileField(tag="s3-tag", null=True, blank=True, max_length=300) How can I get size of file stored on s3? I tried this, but it's not work. def file_size(self): try: prefix = get_file_key(self.s3_file) s3 = boto3.resource("s3") bucket = s3.Bucket() return bucket.Object(prefix).content_length except: pass -
Why it show bad request Bad Request: /updateuser/id/
I am trying to update the User details.I have separate MyUser and Profile models join with a Foreign key relation.I have written a nested serializer UsersProfileSerializer.I want to update both MyUser and Profile details together. When I hit submit then in network I see bad request error.May be I am not passing the correct format of response according to my django rest api.When I tried to print request.POST, it show like this in browser console:(if I want to change address then) { address: Array(1), user: {…}} address: ['Not a valid string.'] user: {username: Array(1), bio: Array(1)} [[Prototype]]:Object Please take a look and suggest me my fault.Thanks in advance. My Models are: class MyUser(AbstractUser): bio = models.CharField(max_length=500, blank=True) is_younger = models.BooleanField(default=False) class Profile(models.Model): genders = [ ("M", "Male"), ("F", "Female"), ] user = models.ForeignKey(MyUser, on_delete=models.CASCADE,related_name="profile") age = models.CharField(max_length=2,blank=True,null=True) gender = models.CharField(max_length=1, choices=genders) contact = models.CharField(max_length=12,blank=True, help_text='Contact phonenumber') address = models.CharField(max_length=100, blank=True) The Serializers are: class ListUsersSerializer(serializers.ModelSerializer): class Meta: model = MyUser fields = ['id', 'username', 'email','bio', 'is_younger'] class UsersProfileSerializer(serializers.ModelSerializer): user = ListUsersSerializer() class Meta: model = Profile fields = ['id','age','gender','contact','address','user'] def update(self, instance, validated_data): user_data = validated_data.pop('user') if user_data is not None: instance.user.id = user_data['id'] instance.user.username = user_data['username'] instance.user.email = user_data['email'] … -
How to change initial value of field if clean_{FOO} is invalid?
I have a ModelForm with a clean function for a field. I want to alter the initial value for the field based on some conditional logic in the field: class MyForm(forms.ModelForm): text_field_1 = forms.CharField() def clean_text_field_1(self): data = self.cleaned_data['text_field_1'] if data == 'Hello': self.fields['text_field_1'].initial = 'Goodbye' return ValidationError('Don't say Hello', code='invalid_input') return data However, I can't access the self.fields property of the form from the clean function (it makes no changes). How do I do this? -
How can I fix/ workaround this KeyError when I try to extract from a json via my python API request?
I have been trying to seed a django DB with some covid data from an api and get a KeyError for a particular data type - in the source it is a floating_timstamp ("lab_report_date" : "2014-10-13T00:00:00.000"). (edit: not sure if the type is relevant, but trying to be comprehensive here). I tried doing a more simple API request in python but get the same keyError. Below is my code and the error message. import requests response = requests.get("https://data.cityofchicago.org/resource/naz8-j4nc.json") print(response.json()) The output looks like this: [ { "cases_age_0_17": "1", "cases_age_18_29": "1", "cases_age_30_39": "0", "cases_age_40_49": "1", "cases_age_50_59": "0", "cases_age_60_69": "0", "cases_age_70_79": "1", "cases_age_80_": "0", "cases_age_unknown": "0", "cases_asian_non_latinx": "1", "cases_black_non_latinx": "0", "cases_female": "1", "cases_latinx": "1", "cases_male": "3", "cases_other_non_latinx": "0", "cases_total": "4", "cases_unknown_gender": "0", "cases_unknown_race_eth": "1", "cases_white_non_latinx": "1", "deaths_0_17_yrs": "0", "deaths_18_29_yrs": "0", "deaths_30_39_yrs": "0", "deaths_40_49_yrs": "0", show more (open the raw output data in a text editor) ... "hospitalizations_unknown_gender": "3", "hospitalizations_unknown_race_ethnicity": "16", "hospitalizations_white_non_latinx": "135" } ] So far so good, but if I try to extract the problem key, i get the KeyError: report_date = [] for i in response.json(): ls = i['lab_report_date'] report_date.append(ls) --------------------------------------------------------------------------- KeyError Traceback (most recent call last) /var/folders/h3/5wlbmz0s3jb978hyhtvf9f4h0000gn/T/ipykernel_2163/2095152945.py in <module> 1 report_date = [] 2 for i in response.json(): ----> … -
Django update index after adding records to db programmatically
I added a number of records to a Django db table (machina forums) directly via a script (ie: I did not use the site admin interface). The structure seemed fairly straightforward with no foreign keys in other tables. However the resulting displays are uneven. In a forum index display all of the children forums display under a category. However if I go into the category, only forums added via the admin interface are visible. There does not appear to be any difference in the db records between those that were added programmatically and those added via the admin interface. I am guessing the issue has to do with indexes on the table. However when I use a GUI to view the db all of the indexes show "result set is empty." Any ideas about what is causing the problem and if it is index related, how do I update the index? -
How to implement an external python code to a Django web server?
as from the title, I am trying to implement an external python code to a Django web server. I am quite new to programming so any hints will be surely helpful. Long story short: I am trying to set up a form where the user have to insert an aminoacidic sequence. This sequence should pass to my python script, that is able to compare it with all the sequences already present in the database and gives as a result the most similar ones. My problem is that I am not able to let my form and my script talk each others. I have followed the Django documentation here https://docs.djangoproject.com/en/3.2/topics/forms/ but this did't helped too much. Also roaming online and browse already asked questions here was unfruitful. Please find here below the files: BLAST_page.html (tried both, commented and uncommented) {% extends "base_generic.html" %} {% block content %} <div class="container-fluid" style="text-align: center;" ></div> <form method="post" action= {% url 'BLAST-process' %}> {% csrf_token %} {{ blast }} <label for="sequence">Type or paste your sequence in the box below</label><br><br> <input type="text" id="sequence" class="input_text" name="sequence" value="{{ sequence }}" style="width:600px; height:200px;"><br><br> <input type="submit" value="Submit"> </form> </div> {% endblock %} <!-- <div class="container-fluid" style="text-align: center;" > <form method="POST" …