Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Uncaught ReferenceError: (function = named as handleTweetActionBtn) is not defined at HTMLButtonElement.onclick ((index):1) [duplicate]
I have been trying to solve this error for quite some time now. The error in the console bar looks like this Console error image I have been trying to develop my logic towards creating like and unlike button. My index.html with script code looks like this {% extends "network/layout.html" %} {% block body %} <div class="row text-center"> <div class="col"> <h2>Welcome to Network</h2> </div> </div> <div class="row mb-3"> <div class="col-md-4 mx-auto col-10"> <form class="form" id="tweet-create-form" method="POST" action="/tweet-create"> {% csrf_token %} <div class="d-none alert alert-danger" id="tweet-create-form-error"> </div> <input type="hidden" value="/" name="next"> <textarea class="form-control" name="content" placeholder="What's happening?"></textarea> <button type="submit" class="btn btn-primary col-12">TWEET</button> </form> </div> </div> <div class="row" id="tweets"> Replace me </div> <script> document.addEventListener('DOMContentLoaded', function() { const tweetCreateFormEl = document.getElementById("tweet-create-form") tweetCreateFormEl.addEventListener("submit", handleTweetCreateFormDidSubmit) const tweetsContainerElement = document.getElementById("tweets") //tweetsElement.innerHTML = "Loading..." // Forms in JS function handleTweetCreateFormDidSubmit(event){ event.preventDefault() const myForm = event.target const myFormData = new FormData(myForm) const url = myForm.getAttribute("action") const method = myForm.getAttribute("method") const xhr = new XMLHttpRequest() const responseType = "json" xhr.responseType = responseType xhr.open(method, url) xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.onload = function() { if (xhr.status === 201){ handleTweetFormError("", false) const newTwt = xhr.response const newTweetElement = formatTweetElement(newTwt) const ogHtml = tweetsContainerElement.innerHTML tweetsContainerElement.innerHTML = newTweetElement + ogHtml myForm.reset() } else if (xhr.status … -
Cannot update model because "id already exists"
I am new to Django and I am trying to use update_or_create in the serializer.create(). However, when I send a request with an existing id for customer, gift or subscription, it shows "id already exists" and does not proceed. What am I doing wrong here? Or is there a completely different way to do this? class SubscriptionSerializer(serializers.ModelSerializer): class Meta: model = Subscription fields = ['id', 'plan_name', 'price'] class GiftSerializer(serializers.ModelSerializer): class Meta: model = Gift fields = ['id', 'plan_name', 'price', 'recipient_email'] class CustomerSerializer(serializers.ModelSerializer): subscription = SubscriptionSerializer(required=False) gifts = GiftSerializer(many=True) class Meta: model = Customer fields = [ 'id', 'first_name', 'last_name', 'address_1', 'address_2', 'city', 'state', 'postal_code', 'subscription', 'gifts'] class RecordSerializer(serializers.ModelSerializer): customer = CustomerSerializer(required=True) class Meta: model = Record fields = ['customer'] def create(self, validated_data): customer_data = validated_data.pop('customer') subscription_data = customer_data.pop('subscription') gifts_data = customer_data.pop('gifts') customer, created = Customer.objects.update_or_create(**customer_data) Subscription.objects.update_or_create(customer=customer, **subscription_data) for gift_data in gifts_data: Gift.objects.update_or_create(customer=customer, **gift_data) record, created = Record.objects.update_or_create(customer=customer, **validated_data) return record -
How to capture logs in django rest framework to database not using any library?
I want to capture my logs in the program, which include INFO, DEBUG, WARN, EXCEPTION to the database. without using any django libraries. Please have a look -
Django Model Import Error When trying to Import in Another App's Model
I'm working on a Django based project right now. I 'm getting an error something called AppRegistryNotReady when I'm trying to import a model into another app's model with django get_model() method.. Now the interesting this is, I can import the models from another app in the view files with the same get_model() method. In views file: from django.apps import apps Course = apps.get_model('course', 'Course') Order = apps.get_model('course', 'Order') *Now everything is working parfectly. In models file: from django.apps import apps Course = apps.get_model('course', 'Course') Order = apps.get_model('course', 'Order') *Now it is getting the following error: File "/home/mohul/.local/share/virtualenvs/django-backend-and-view-1OsDTUBe/lib/python3.9/site-packages/django/apps/registry.py", line 141, in check_models_ready raise AppRegistryNotReady("Models aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. -
Django assign user to group during registration based on choice in another field
I would like to automatically assign users to a group based on their choice in another field in the user registration field. I am new to Django and I am not sure of the best way to achieve this. I want to assign the group based on the choice of the "business_location_county" field in the model. In simple terms the group should be the group id where the group "forum_id" equals the id of the business_location_county choice. The group "forum_id" is a custom column added to the Group model. The models.py: from django.contrib.auth.models import AbstractUser from django.db import models from machina.core.db.models import get_model from django.db.models import Q from django.contrib.auth.models import Group Forum = get_model("forum", "Forum") class CustomUser(AbstractUser): age = models.PositiveIntegerField(null=True, blank=True) business_location_state = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, limit_choices_to={"lft":1}) business_location_county = models.ForeignKey(Forum, null=True, on_delete=models.SET_NULL, related_name='county', limit_choices_to=(~Q(lft__in = (1,2)))) Group.add_to_class('forum_id', models.PositiveIntegerField(null=True, blank=True)) views.py: from django.urls import reverse_lazy from django.views.generic import CreateView from .forms import CustomUserCreationForm from .models import CustomUser from django.shortcuts import render from machina.core.db.models import get_model from django.db.models import Q Forum = get_model("forum", "Forum") class SignUpView(CreateView): form_class = CustomUserCreationForm success_url = reverse_lazy('login') template_name = 'registration/signup.html' def load_counties(request): parent_id = request.GET.get('business_location_state') counties = Forum.objects.filter(parent_id=parent_id).order_by('name') return render(request, 'hr/county_dropdown_list_options.html', {'counties': counties}) forms.py: from django import … -
django get data with filter today
i want to get Device created today this is my model : class Device(models.Model): hostname = models.CharField(max_length=200, null=True) password = models.CharField(max_length=200, null=True) type = models.CharField(max_length=200,choices=dtype, null=True) ipadress = models.CharField(max_length=200, null=True) date_created = models.DateTimeField(auto_now_add=True, null=True) and i tried this views but didn't work : device_today = Device.objects.filter(date_created=today).count() any advice ? -
Github Auth using Django + React
The problem: Hi, guys! I've been trying to implement Github auth with Django + SPA (React in this case). Something as basic as it can be. But still i'm not able to complete the full workflow. I tried 3 or 4 djangopackages, among them: drf-social-oauth2, social-app-django, python-social-auth. But i couldn't make them work! Maybe I'm dumb, I don't know! The thing is that I could kinda complete the process of getting an access_token from Github. Im using: Django==3.2.4 django-cors-headers==3.7.0 djangorestframework==3.12.4 djangorestframework-simplejwt==4.4.0 PyJWT==1.7.1 What I've tried: This is the workflow from Github docs: here. Basically we need to make a GET request with our CLIENT_ID (you get this from Github by "creating an app") to this endpoint github.com/login/oauth/authorize. The user is gonna get asked if he authorize the app to access their personal information. The user accepts and Github fires a callback function with a CODE as url a param: import asyncio from .github import Github from rest_framework.generics import GenericAPIView from rest_framework.response import Response class CallbackAPIView(GenericAPIView): """ This endpoint receives the CODE and exchange it to a token """ def get(self, request): code = request.query_params.get('code', None) data = asyncio.run(Github.request_access_token(code)) access_token = data.get('access_token') user_email = asyncio.run(Github.get_user_email(access_token)) user = Github.register_or_authenticate( user_email=user_email, access_token=access_token) return … -
migration not working with django and docker?
I have a project where I have developed a Django application which I am trying to containerize and host on my raspberry pi. During development on my local environment the container is working fine (builds and run without any errors). However when I try to run it on my server the migrations just wont work. For some strange reason it is not including my custom user model during migrations. The file structure follows a basic pattern with one folder for the app, and another containing the webserver (nginx). The Django-compiler creates three images (postgres, django, nginx). The main logic related to the Containers could be found in the main Dockerfile. To run the migrations and start the django application Ive included a bash script that migrates all models. However, during the build I get the following error: app_1 | False app_1 | Operations to perform: app_1 | Apply all migrations: admin, auth, contenttypes, sessions, token_blacklist app_1 | Running migrations: db_1 | 2021-06-14 00:36:00.879 UTC [35] ERROR: relation "users_newuser" does not exist db_1 | 2021-06-14 00:36:00.879 UTC [35] STATEMENT: ALTER TABLE "django_admin_log" ADD CONSTRAINT "django_admin_log_user_id_c564eba6_fk_users_newuser_id" FOREIGN KEY ("user_id") REFERENCES "users_newuser" ("id") DEFERRABLE INITIALLY DEFERRED app_1 | Applying admin.0001_initial...Traceback (most recent call … -
Django AttributeError when attempting to save objects to database through model.py
I am working on a web-app that searches the IGDB database for games of a user chosen title, then displays them on screen. Users will be able to click an add button to add the chosen game to their personal collection as a user. Right now I am working on the database models and I am having trouble with the collections model I am building. I want to be able to save each game under a user specific collection. This is my models.py: from django.db import models from django.contrib.auth.models import User # Create your models here. class Game(models.Model): collector = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50, blank=True, null=True) cover = models.CharField(max_length=50, blank=True, null=True) storyline = models.TextField(max_length=500, blank=True, null=True) summary = models.TextField(max_length=500, blank=True, null=True) genre_set = models.CharField(max_length=50, blank=True, null=True) def __str__(self): return self.name class Collection(models.Model): from .views import save collector = models.ForeignKey(User, on_delete=models.CASCADE) colletion = models.ManyToOneRel(save.game_data, null=True, blank=True) def __str__(self): return self.name pass class Counter(models.Model): def increment(self): self.counter += 1 def get_value(self): return self.counter This is my saving function in views.py: from igdb.wrapper import IGDBWrapper from django.views.generic import ListView from catolog.models import Game from django.shortcuts import render import json import requests exp_time = False # Create your views here. def save(request, message_json): … -
Uploading an image to backend works with Postman but not in my React app
My application is using django rest framework for the backend and react on the frontend. I have a model Place which has several fields, one of which is a photo. I have a front end form that connects to the api endpoint to create a new Place model. Whenever I submit the form through my react form (with the file included), the server responds with a 200 but does not actually save anything to the db. Whenever I submit the form without the file through my react app, it saves the other data successfully. The weird thing is, I can get it to work without a problem using Postman, so my guess is the problem lies within the react component / HTML form. Here is the react component with form: import React, {useState, useContext, useRef} from "react"; import AuthContext from '../store/auth-context'; function NewPlaceForm(props) { const authCtx = useContext(AuthContext); const nameInputRef = useRef(); const latInputRef = useRef(); const longInputRef = useRef(); const completedInputRef = useRef(); const dateCompletedInputRef = useRef(); const photoInputRef = useRef(); const notesInputRef = useRef(); const userId = localStorage.getItem('userId'); const submitHandler = (event) => { event.preventDefault(); const enteredName = nameInputRef.current.value; const enteredLat = latInputRef.current.value; const enteredLong = longInputRef.current.value; const … -
Django Rest Framework "Page Not Found" Error when using drf-nested-routers
We have an API that allows users to save their inventory of player profiles. The API endpoint for that is: /api//api/inventory-live-collection/ /api/inventory-live-collection/20 # gets a single listing from InventoryLiveCollection However, one of the fields inside of this response is very large, so we would like to be able to paginate it and make a request such as: /api/inventory-live-collection/20/needed-inventory/ According to the docs, the drf-nested-routers package is the way to handle this. The docs also made it look extremely simple to use, but I must be missing something, as I get a "Page Not Found" error. Here is the urls.py : router = routers.DefaultRouter() router.register(r'inventory-live-collection', views.InventoryLiveCollectionView) inventory_live_collection_router = routers.NestedSimpleRouter( router, r'inventory-live-collection', lookup='inventory_live_collection' ) inventory_live_collection_router.register( r'needed-inventory', views.NeededInventoryView, basename='needed-inventory' ) urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)), path('api/inventory-live-collection/', include(inventory_live_collection_router.urls)), ] views.py class NeededInventoryView(viewsets.ModelViewSet): def get_queryset(self): return PlayerProfile.objects.filter(inventory_live_collection=self.kwargs['inventory_live_collection_pk']) I don't think the model is the issue, but here is the model.py. class PlayerProfile(models.Model): card_id = models.CharField(max_length=120, unique=True, primary_key=True) name = models.CharField(max_length=120, null=True) class InventoryLiveCollection(models.Model): needed_inventory = models.ManyToManyField(PlayerProfile, related_name="needed_inventory") date = models.DateTimeField(null=True, blank=True) Where did I go wrong? Can someone point me in the right direction? -
django error in import users.signals into apps.py in users app
following is my settings.py installed app section INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # third party 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'allauth', 'allauth.account', 'allauth.socialaccount', 'rest_auth.registration', 'corsheaders', 'crispy_forms', # local apps 'users.apps.UsersConfig', ] AUTH_USER_MODEL = 'users.CustomUser' following is my apps.py file content from django.apps import AppConfig class UsersConfig(AppConfig): name = 'users' def ready(self): import users.signals following is my signal.py file content from django.db.models.signals import post_save from django.contrib.auth.models import User from django.dispatch import receiver from .models import Profile @receiver(post_save, sender=User) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.profile.save() init.py file in users app is empty when I run command python manage.py makemigrations it gives error ModuleNotFoundError: No module named 'users.users' and also it shows error "No module named users" in the following line in apps.py import users.signals my project directory sctructure screenshot is as shown in attached picture [enter image description here][1] [1]: https://i.stack.imgur.com/PNU7p.png with reference to above django configuration/code what correction in needed to resolve error in apps.py so that no module named users is resolved and signals are loaded correctly for the users app -
Why does my pre-signed URL for my s3 bucket look different when deployed?
My python (Django) application stores confidential documents and has a private bucket in AWS S3. When you make a request for the resource, it uses boto3 to generate a pre-signed URL to be able to download the document. The code to do so is as follows: @staticmethod def create_presigned_url(key_name, bucket_name=settings.AWS_PDF_STORAGE_BUCKET_NAME, expiration=60): """ Generate a pre-signed URL to share a PDF. :param key_name: string. :param bucket_name: string. :param expiration: Time in seconds for the pre-signed url to remain valid. :return: Pre-signed URL as a string. If error, returns None. """ s3_client = boto3.client('s3') try: response = s3_client.generate_presigned_url( 'get_object', Params={'Bucket': bucket_name, 'Key': f"pdf/{key_name}"}, ExpiresIn=expiration ) except ClientError: return None return response When I run my application locally, it works great. It generates a link I can use to download the document and it expires after 60 seconds. Such URL looks like this: https://BUCKETNAME.s3.amazonaws.com/pdf/testuser1/dummy.pdf?AWSAccessKeyId=ACCESSKEY&Signature=SIGNATURE&Expires=EXPIRATION" I then deploy my application to AWS Elastic Beanstalk. All the same environment variables with AWS secrets are configured. But when I run the same request, I get a much longer URL that looks like this: https://fiber-staging-pdfs.s3.amazonaws.com/pdf/liza/dummy.pdf?AWSAccessKeyId=ACCESSKEY&Signature=SIGNATURE&x-amz-security-token=TOKEN&Expires=EXPIRATION Somehow, the same code when run against this environment is adding a x-amz-security-token parameter? Why? And When I try to visit this … -
Asking for an approch to start building an Analysis app for top management industrial company
I want your suggestions to start a simple software developement. I'm an intern student and i want to build, preferably, something that can be acceced with a user authentication to a specific number of users < 5 so that each one of them can access the analysis of the data that concerns him. Preferably : I want my users to get to the app through the browser The users are those who will provide data to the app through an upload file button so this latter can output the whole analysis the app should have a professional look I'm supposed to work with these four-five peapole to determine what they want to see so i can prepare all the analysis code that corresponds to the right feeded data. genrally the data will have csv excel format. I've start working with R shiny then I built a single shiny app for control and mangement director that contains a dahsboard with analysis/viZ elements. Then i figured out that I cannot add the feature of multiple users and neither the authotication feature. then I've start learning django but i realized that it's quite harder to do it in a month. I searched for … -
Django didnt receive email
i am trying to send email from the website that i create. It does not display any error but there are no email that I received. here is my setting code EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myemail@gmail.com' EMAIL_HOST_PASSWORD = 'my email's pswrd' EMAIL_PORT = 587 EMAIL_USE_TLS = True Here is the function from django.core.mail import send_mail def sentmes(request): if request.method == "POST": name = request.POST.get('name') email = request.POST.get('email') subject = request.POST.get('subject') message = request.POST.get('message') data = { 'name': name, 'email': email, 'subject': subject, 'message': message } mail = ''' New message: {} From: {} '''.format(data['message'], data['email']) send_mail(data['subject'], mail, ' ', ['myemail@gmail.com'], fail_silently=False) return render(request, ' ') this is the output that i get [14/Jun/2021 06:52:15] "POST / HTTP/1.1" 200 18516 Where is my mistake. Hope someone can help. Thank you. -
Suggest method in creating new app within Django Oscar apps
I would like to add another app called projects to list project and view single project along with Oscar. I am trying to work out what is the correct method to do this? Do I write python3 manage.py startapp project under Django Oscar or fork catalogue and rename to projects. What suggestion should I do to create and setup new app called project? -
How to prevent django from swapping primary key values
I am creating a Django web app. I have set a field as a primary key and a unique field. When I try to edit it and give it the same value as another item in the primary key column, the current item got duplicated and each value goes to one of them as shown below. This is my code from models.py: class Car(models.Model): class Meta: verbose_name = "Car" verbose_name_plural = "Cars" car_id = models.CharField(verbose_name='Car ID', max_length=10000, primary_key=True, unique=True) Some screenshots from the admin panel: -
How to render Custom Django Widget as Buttons for ChoiceField?
I have a Django reviewing and photo sharing application. When a user submits a new Review instance, they can indicate the 'Method of Consumption' using Select widget, which by default will show choices as a dropdown. This is a very bland look. I want to use a custom Widget which will render the choices as buttons. This is far more visually appealing. How do I render the widget such that for each choice, there is a button with value equal to the choice (Flower, Extract, Edible)? Currently, only one button is displayed with 'None' value. models.py class Review(models.Model): title = models.CharField(max_length=35) content = models.TextField(max_length=500) strain = models.ForeignKey( Strain, on_delete=models.CASCADE, related_name="user_review" ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.PROTECT, related_name="user_reviews", default=1 ) photo = models.ImageField( upload_to=upload_location, blank=True, null=True, height_field="height_field", width_field="width_field", ) height_field = models.IntegerField(default=0, null=True) width_field = models.IntegerField(default=0, null=True) FLOWER = 'Flower' EXTRACT = 'Extract' EDIBLE = 'Edible' METHOD_CHOICES = ( (FLOWER, 'Flower'), (EXTRACT, 'Extract'), (EDIBLE, 'Edible'), ) method = models.CharField( max_length=20, choices=METHOD_CHOICES, default='Flower', blank=False ) RATING_CHOICES = ( (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ) rating = models.IntegerField(choices=RATING_CHOICES, default=5) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True) updated = models.DateTimeField(auto_now=True, auto_now_add=False) users_like = models.ManyToManyField( settings.AUTH_USER_MODEL, related_name="reviews_liked", blank=True ) class Meta: ordering = … -
Django - How to get count of all sub-fields connected with object
I am trying to make some kind of points system that would gather count of segments Here's how the models are structured: from django.db import models # Create your models here. class Person(models.Model): name = models.CharField(max_length=64) class Event(models.Model): name = models.CharField(max_length=64) class Segment(models.Model): name = models.CharField(max_length=64) event = models.ForeignKey(Event, on_delete=models.CASCADE) class Presence(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) segments = models.ManyToManyField(Segment) Basically I'm looking for the best way to get the count of segments in which Person has taken part in, f.e.: John = Person Instance() Event1 = Event Instance() Event2 = Event Instance() Segment1 = Segment Instance(event=Event1) Segment2 = Segment Instance(event=Event1) Segment3 = Segment Instance(event=Event2) Segment4 = Segment Instance(event=Event2) Segment5 = Segment Instance(event=Event2) Presence1 = Presence Instance( person = John, segments = [ Segment1, Segment4, Segment5, ] ) Presence2 = Presence Instance( person = John, segments = [ Segment2, Segment3, ] ) What I'm looking for is the way to count that John has taken part in 5 segments If this could be helpful, I will be using it in django-rest-framework so if it's easier to do it directly in there I'm open to any suggestions Also is there a way to connect ManyToManyField choice with Foreign Key like that: class … -
How to add AJAX Mixin to CreateView
I have been adding AJAX functionality by creating separate FBVs which specifically handle AJAX, but I would like to add AJAX functionality directly to a CreateView. I see in the documentation where there is a JSONResponseMixin but I do not want a JSON response. I would rather the view just send back an HTTPResponse ie render(request, template, context) so that I can handle the HTML easily on the front-end. How can I do this using a Mixin? CreateView: class MCQuestionCreateView(PermissionRequiredMixin, LoginRequiredMixin, CreateView): model = MCQuestion template_name = 'quiz/mcquestion_form.html' form_class = MCQuestionForm success_url = reverse_lazy('questions') permission_required = 'quiz.add_question' permission_denied_message = 'User does not have permissions to create questions.' def get_form_kwargs(self): kwargs = super(MCQuestionCreateView, self).get_form_kwargs() kwargs.update({'user': self.request.user}) return kwargs def get_context_data(self, **kwargs): data = super(MCQuestionCreateView, self).get_context_data(**kwargs) if self.request.POST: data['answers'] = AnswerFormSet(self.request.POST) else: data['answers'] = AnswerFormSet() return data def form_valid(self, form): context = self.get_context_data() answers = context['answers'] with transaction.atomic(): self.object = form.save() if answers.is_valid(): answers.instance = self.object answers.save() return super(MCQuestionCreateView, self).form_valid(form) I have tried overriding the get method but it seems to redirect any time I make the AJAX call. Then I get this error int he console (among others): VM19 jquery.min.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of … -
Invalid block tag on line 9: 'static', expected 'endblock'. Did you forget to register or load this tag?
I am getting an error with Django where I am attempting to link a second stylesheet to an html document that extends from a base template. The base template has a stylesheet already linked. Here is the section of the base template: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link href="{% static 'encyclopedia/styles.css' %}?{% now 'U' %}" rel="stylesheet"> {% block styles %} {% endblock %} </head> And here is the html document that extends from the base template: {% extends "encyclopedia/layout.html" %} {$ load static %} {% block title %} New Entry {% endblock %} {% block styles %} <link rel="stylesheet" href="{% static 'encyclopedia/new-entry.css' %}?{% now 'U' %}"> {% endblock %} I'm not sure why the static tag in the second html document is "breaking" the styles block. I looked into some similar threads but couldn't figure out what I was doing differently, as this appeared to have worked for others. -
Object of type 'xxx' is not JSON serializable Django UpdateView
I am trying to edit with UpdateView a form after I have entered and saved the information. I send the parameters with AJAX from the view, however I get the error: "Object of type Form is not JSON serializable". Attached are some related code snippets. models.py class Formulario(models.Model): creado_el = models.DateTimeField(_('creado el'), null=False, blank=True, default=tz.now) fecha_ingreso = models.DateTimeField(auto_now_add=True, null=True, blank=True) monto = models.CharField(_('monto'), null=False, blank=False, max_length=40) plazo_meses = models.CharField(_('plazo meses'), null=False, blank=False, max_length=40) nombre_1 = models.CharField(_('nombre 1'), max_length=40, null=False, blank=False) nombre_2 = models.CharField(_('nombre 2'), max_length=40, null=True, blank=True) # Puede estar en blanco apellido_1 = models.CharField(_('apellido 1'), max_length=40, null=False, blank=False) apellido_2 = models.CharField(_('apellido 2'), max_length=40, null=True, blank=True) tipo_doc = models.ForeignKey(TipoDocumento, on_delete=models.SET_NULL, null=True) dni = models.CharField(_('dni'), max_length=20, null=False, blank=False) f_nacimiento = models.DateField(_('f_nacimiento'), null=False, blank=False) email_1 = models.EmailField(_('email 1'), max_length=254, null=False, blank=False) celular = models.IntegerField(_('celular'), null=False, blank=False) e_civil = models.ForeignKey(EstadoCivil, on_delete=models.SET_NULL, null=True) genero = models.ForeignKey(Genero, on_delete=models.SET_NULL, null=True) dependientes = models.ForeignKey(Dependientes, on_delete=models.SET_NULL, null=True) tipo_ingreso = models.ForeignKey(TipoIngreso, on_delete=models.SET_NULL, null=True) salario = models.DecimalField(_('salario'), max_digits=6, decimal_places=2, null=False, blank=False) empresa_1 = models.CharField(_('empresa'), max_length=50) in_extras = models.ForeignKey(IngresosExtra, on_delete=models.SET_NULL, null=True) estudios = models.ForeignKey(Escolaridad, on_delete=models.SET_NULL, null=True) p_expuesto = models.ForeignKey(PEP, on_delete=models.SET_NULL, null=True) # ciudad = models.CharField(_('ciudad'), max_length=40, null=False, blank=False) # Lugar de residencia, dirección # sector = models.CharField(_('sector'), max_length=40, null=False, blank=False) provincia … -
m2m form to connect a profile to another model, Django
I have a many-to-many relationship that is connected to a model "profile". The idea is to allow every user to chose as many SDGs as he wants and to create a connection between them. However, whenever I save this relation, the new object is not being added to the database but no errors are being created. In case anyone has an idea why this is happening, it would be awesome. So here is my code: models.py class Profile(models.Model): id = models.CharField(max_length=50, primary_key= True) user = models.OneToOneField(User, on_delete=models.CASCADE) sdg = models.ManyToManyField(SDG, through="SDG_User") background_picture = models.ImageField(upload_to=profile_pic_directory_path,default="Null") profile_picture = models.ImageField(upload_to=profile_pic_directory_path,default="Null") class SDG_User(models.Model): sdg = models.ForeignKey(SDG, on_delete=models.CASCADE) user_id = models.ForeignKey(Profile, on_delete=models.CASCADE) class SDG(models.Model): title = models.CharField(max_length=50, unique=True) contenu = models.TextField(default="NA") image = models.ImageField(upload_to='sdgs/') def __str__(self): return '{} - {}'.format(self.title, self.contenu) forms.py class SDGForm(forms.ModelForm): sdg = forms.CheckboxSelectMultiple() class Meta: model = Profile fields = ('sdg',) views.py def edit_profile_sdgs(request): if request.method == 'POST': sdg_form = SDGForm(request.POST,instance=request.user) if sdg_form.is_valid(): sdg = sdg_form.save(commit=False) sdg.user = request.user sdg.save() sdg_form.save_m2m() messages.success(request, 'if') return redirect(reverse(("accounts:user_profile"),args=[request.user.username])) else: sdg_form = SDGForm(instance=request.user) return render(request, 'dist/inside/profile/edit/edit_sdg.html', { 'sdg_form': sdg_form, }) -
Heroku, problem running django app due to bash: ps:scale: command not found
I just tried for the first time Heroku to deploy to pre-production. After building the app successfully connecting it to GitHub, I got an H14 error when visiting the app. After adding the Procfile + adding heroku ps:scale web=1, Checking the logs I get the following(along with an H14 error after) 2021-06-13T20:31:48.547165+00:00 heroku[heroku.1]: State changed from crashed to starting 2021-06-13T20:31:54.889231+00:00 heroku[heroku.1]: Starting process with command `ps:scale web=1` 2021-06-13T20:31:55.562137+00:00 heroku[heroku.1]: State changed from starting to up 2021-06-13T20:31:57.440662+00:00 app[heroku.1]: bash: ps:scale: command not found 2021-06-13T20:31:57.518775+00:00 heroku[heroku.1]: Process exited with status 127 2021-06-13T20:31:57.661020+00:00 heroku[heroku.1]: State changed from up to crashed 2021-06-13T20:31:59.000000+00:00 app[api]: Build succeeded 2021-06-13T20:32:06.712436+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET Anyone has a clue on why this might be? -
How to debug a Django view through Heroku?
I found a bug in my web application and I am trying to debug one of my views through the LOGGER to visualize the results that my code is generating. This is the code implementation: import logging .... @login_required def retrieve_results(request): template_name = 'task/formRetrieval.html' status = 'In Progress' status_task = 'Active' logging.basicConfig(filename='std.log', filemode='w' format='%(asctime)s,%(msecs)d %(name) %(levelname)s %(message)s', level=logging.DEBUG) logger = logging.getLogger() qs_current = Task.objects.filter(accounts=request.user.id).values('id').values_list('id') logger.debug(str(qs_current)) ... The output is an empty std.log file, no result was logged. I am wondering if there's a permission problem that prevents my code from writing files into the heroku container. I even went a step further and I decided to create a txt file and I tried to log the results there but I only found an empty file. I have some questions: If Heroku is preventing me from creating a new file then is there a solution to indicate that logging files should be allowed? How can I indicate to Django to log a new file? Any help or suggestion is really appreciated :) Thank you