Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Formsets are returning as valid=False and not saving
I'm trying to create a form that allows teachers to create lessons, which are linked to multiple activities (ManyToMany), which are in turn linked to many Items (ForeignKey). As such, I am using formsets for activities and items. However, activity_formset is coming back as invalid and not saving. The View class N_LessonEditAllView(LoginRequiredMixin, UpdateView): model = Lesson template_name = 'lessons/edit-lesson.html' form_class = LessonForm def get_object(self): return get_object_or_404(Lesson, pk=self.kwargs.get('pk')) def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) lesson = self.get_object() activity_formset = ActivityFormSet(queryset=lesson.activity.all()) item_formsets = [] for activity_form in activity_formset: item_formset = ItemFormSet(queryset=Item.objects.filter(activity_id=activity_form.instance.id)) item_formsets.append(item_formset) context['activity_formset'] = activity_formset context['item_formsets'] = item_formsets return context def form_valid(self, form): context = self.get_context_data() activity_formset = context['activity_formset'] item_formsets = context['item_formsets'] print('activity_formset is valid:', activity_formset.is_valid()) print('activity_formset errors:', activity_formset.errors) for activity_form in activity_formset: item_formset = ItemFormSet(queryset=Item.objects.filter(activity_id=activity_form.instance.id)) item_formsets.append(item_formset) print(f'activity_formset for activity {activity_form.instance.id} is valid: {item_formset.is_valid()} --- data {activity_formset.data} --- errors: {activity_formset.errors} --- payload {self.request.POST}') if activity_formset.is_valid() and all(item_formset.is_valid() for item_formset in item_formsets): self.object = form.save() activity_formset.instance = self.object activity_formset.save() print('Form is valid:', form.is_valid()) print('Activity formset is valid:', activity_formset.is_valid()) for item_formset in item_formsets: print('Item formset is valid:', item_formset.is_valid()) item_formset.instance = self.object item_formset.save() raise ValueError('Intentional error') print(form.cleaned_data) return super().form_valid(form) else: return self.form_invalid(form) The Template <div class="card"> <form method="post"> <div class="card-header"> {% csrf_token %} {{ form|crispy … -
How to make Django ModelForm filed to update the attrs, so the style can be displayed successfully
from django.forms import ModelForm from django import forms from .models import Project class ProjectForm(ModelForm): class Meta: model = Project fields = ['title', 'featured_image', 'description', 'demo_link', 'source_link', 'tags'] widgets = { 'tags': forms.CheckboxSelectMultiple(), } def __int__(self, *args, **kwargs): super().__int__(*args, **kwargs) # self.fields['title'].widget.attrs.update({'class': 'input'}) for name, field in self.fields.item(): field.widget.attrs.update({'class': 'input'}) I AM TRYING TO DISPLAY MY DYNAMIC FORM WITH THE CORRECT STYLING, BUT THIS METHOD DOESN'T SEEM TO WORK Does anybody know how to fix it? Thank you so much for the help in advance ` def __int__(self, *args, **kwargs): super().__int__(*args, **kwargs) # self.fields['title'].widget.attrs.update({'class': 'input'}) for name, field in self.fields.item(): field.widget.attrs.update({'class': 'input'})` This doesn't seem to work -
Displaying an image stored in a Django database
I have a website dedicated to pets (dead ones), and I have some stock images in the database stored under the pet using a manytomany field (so, any number of pets can be in an image, and a pet can have any number of images associated with it--seems logical so far). I am trying to display the pet photos in any way at all in one of the templates. My problem is, I have NO IDEA what the correct syntax for iterating over a context_dictionary data structure I have made to store pets and pet photos for the purpose of accessing in the associated template file. I am having to do this because I think (correct me if I'm wrong) a view can only have one associated model, and I need a few models, their data, to display in one view. So. It is what it is. I think it's probably about time I showed some of my code. Here is one after another: pet_profile/models.py from django.db import models from django.utils.crypto import get_random_string import uuid from django.urls import reverse class PetPhoto(models.Model): slug = models.SlugField(max_length = 5, primary_key = True, blank = True, null=False) title = models.CharField(max_length = 255) id = … -
Incorrect floating label positioning on responsive input form
I've created a form using Django, Crispy Forms and Bootstrap. At screen widths above 575px the form and labels look as expected with fields of the correct width and floating labels in the correct position, however at screen widths below 575px the floating labels appear in the wrong position. I'd appreciate any guidance as to how I can make the floating labels remain in the correct position relative to the input field regardless of screen width. Expected: >575px Unexpected: <575px I believe this happens because, in order to force the responsive resizing of the input fields, I manually amended the CSS to reduce the the field width to 85% at screen widths lower than 575px by using a media query as follows: CSS .form-floating { position: relative; } .form-floating > .form-control, .form-floating > .form-select { height: calc(3.5rem + 2px); line-height: 1.25; } .form-floating > label { position: absolute; top: 0; left: 0; height: 100%; padding: 1rem 0.75rem; pointer-events: none; border: 1px solid transparent; transform-origin: 0 0; transition: opacity 0.1s ease-in-out, transform 0.1s ease-in-out; } @media (max-width: 575px) { .form-floating > .form-control, .form-floating > .form-select { display: block; width: 85%; padding: 0.375rem 0.75rem; margin: 0 auto; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: … -
Django model-chain, im not reaching bottom from top
class Firma(models.Model): #company isim = models.CharField(max_length=20) def __str__(self): return f"{self.isim}" class Proje(models.Model): #project isim = models.CharField(max_length=20) #name projeBedeli = models.DecimalField(max_digits=20, decimal_places=0) #total project cost projeKalantutar = models.DecimalField(max_digits=20, decimal_places=0) #remaining project cost projeTarih = models.DateField() #project date firma = models.ForeignKey(Firma, on_delete=models.CASCADE) #company def __str__(self): return f"{self.isim} {self.projeBedeli} {self.projeKalantutar} {self.projeTarih}" class Odeme(models.Model): #payment hakedisAdi = models.CharField(max_length=20) #WpName hakedisTutar = models.DecimalField(max_digits=20, decimal_places=0) #WpPrice hakedisTarih = models.DateField() #Date proje = models.ManyToManyField(Proje, through='Santiye') #project def __str__(self): return f"{self.hakedisAdi} {self.hakedisTutar} {self.hakedisTarih} {self.proje}" class Araclar(models.Model): #tools tip = models.CharField(max_length=20) #type def __str__(self): return f"{self.tip}" class Santiye(models.Model): #Work field butce = models.ForeignKey(Odeme, on_delete=models.CASCADE, null=True, default=0) #budget proje = models.ForeignKey(Proje, on_delete=models.CASCADE) #project isim = models.CharField(max_length=50) #name araclar = models.ManyToManyField(Araclar) #tools def __str__(self): return f"Birim : {self.isim} / Şantiye Bütçesi : {self.butce} / Bağlı Olduğu Proje : {self.proje} / Kullanılan Araçlar : {self.araclar}" class Personel(models.Model): #Workers ad = models.CharField(max_length=50) #name cinsiyet = models.CharField(max_length=10) #gender yas = models.DecimalField(max_digits=4, decimal_places=0) #age baslamaTarih = models.DateField() #date resim = models.FileField(default="static/images/avatar.jpg") #avatar birim = models.ForeignKey(Santiye, on_delete=models.CASCADE, null=True, default='') #which work field def __str__(self): return f"{self.ad} {self.cinsiyet} {self.yas} {self.baslamaTarih} {self.birim}" I am not sure this models.py perfectly fits with this diagram to be honest.. Here is the link of ERD Diagram : https://ibb.co/7GchYCM Actually I want … -
wfastcgi-enable.exe is not recognize on python 3.10.10
How can I configure a Django Project on IIS without wfastcgi.py? I don't found any wfastcgi.py in python's 3.10.10 folder. Anyone could help me? I tried at least 5 tutorials on youtube, but everyone requires wfastcgi.py. I've expected anyone could help me to solve this issue. -
Html Form Posting Values to Django Backend only when submitted twice, or rather hit back to form and then submit again
So I have stumbled upon a case where my form does not post values after I click the submit button once, it goes to the next page indeed but my Django View can not fetch the post values. But soon after I hit back button on browser and then clicks the submit button again it works ; I can then see the POSTed values in my DJango Views. Here's my HTML form. (Please note I have removed the unnecessary code which is long) <form action="" method="POST" id="quizform"> {% csrf_token %} <fieldset class="cfield" id="box1"> <p id="question" class="fs-title"> 1. {{data.0.question}}</p> <div class="row"> <div class="{% if data.0.correct_answer2 == "" %}col-12{% else %}col-9{% endif %}"> <div class="form-check"> <label class="form-check-label"> <img id="a1-icon-{{data.0.pk}}" src="/static/assets/img/correct.png" class="answer_icon" width="20px" style="z-index: 99;" hidden> <input id="a1{{data.pk}}" style="z-index: -1;" type="radio" class="radiobox form-check-input radio-box ans" name="q{{data.0.pk}}" qid="{{ data.0.pk }}" value="{{data.0.a1}}" required {% if data.0.correct_answer2 != "" %}disabled{% endif %}> <span class="cspan" style="color: white;">TES</span> </label> <span id="a1" class="cspan">{% if data.0.a1_image.url != None %}<img src="{{ data.0.a1_image.url }}" class="" width="100px">{% endif %} {{data.0.a1}} </span> </div> <div class="form-check"> <label class="form-check-label"><img id="a2-icon-{{data.0.pk}}" src="/static/assets/img/correct.png" class="answer_icon" width="20px" style="z-index: 99;" hidden> <input id="a2{{data.pk}}" style="z-index: -1;" type="radio" class="radiobox form-check-input radio-box ans" name="q{{data.0.pk}}" qid="{{ data.0.pk }}" value="{{data.0.a2}}" required {% if data.0.correct_answer2 != "" … -
My comment form does not appear on the template page (django)
My codes work on local but not work on the net :) Here is my simple django blog website. When i tested these codes work but when i try live version, it doesnt work. Where is the my fault? If you wanna see the live page you can look this page https://www.endustri.io/kaynak-perdesi-nedir-ne-ise-yarar-cesitleri-fiyatlari/ I added two types comment section the template page but none of them work. Here is my codes; blog post codes page (detail.html) {% extends 'blog/base1.html' %} {% load static %} {% block content %} <head>{% block title %}<title>{{ post.title }} - Endustri.io</title>{% endblock %}</head> <div class="card"> <h5 class="card-header">{{ post.title }}</h5> <div class="card-body"> <h6 class="card-title">Yazar: {{ post.author.first_name }} {{ post.author.last_name }} - Tarih: {{post.date_added}} - Kategori: <a href="{% url 'category' post.category.slug %}"> {{ post.category.title }}</a> <hr/></h6> <p class="card-text">{{ post.body|safe }}</p> </div> </div> <div class="card"> <h5 class="card-header">Yorumlar</h5> <div class="card-body"> <h6 class="card-title"> {% for comment in comments %} <article> <strong>{{ comment.name}} at {{ comment.date_added }}</strong></br> {{ comment.body }} </article> {% endfor %}</h6> </div> </div> <form method="POST" class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit">Yorum Ekle</button> </form> <br> <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.as_p }} <button type="submit">Add comment</button> </div> </form> {% endblock %} Comment model class Comment(models.Model): … -
(No asignation direction ipv6 in docker) /usr/bin/env: ‘bash\r’: No such file or directory
Soy nuevo en esto, estoy tratando de clonar un repositorio de GitHub, trabajo con el docker, en el powershell, creo la carpeta, descargo el repositorio, abro la carpeta del repositorio, ejecuto la instrucción docker compuse build, pero al ejecutar el docker compouse up, me da la direccion ipv4 pero la direccion ipv6 no, en el docker me crear los contenedores pero al iniciarlos, no hace nada. Intenté de nuevo, creando otra carpeta, sigue igual -
How to decode uidb64 from activation link's url Django
i hope you are all doing well. I am working on a django project with MySQL. I am working on the signup part for the candidate with an activation link sent in the email. When i connected django to MySQL Workbench, It generated a Model file including the "Candidats form" which iam using in my view. The problem is that i cannot decode the uidb64 from the url. I can send a link in the email but it always return "Activation went wrong" and when i debugged my code i found out that my methid is not returing the uid but None. This is my view.py from django.urls import reverse from .tokenssss import token_generator from django.core.mail import EmailMessage from django.contrib.sites.shortcuts import get_current_site from django.shortcuts import render from django.http import HttpResponse from django.utils.encoding import force_bytes, force_str from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.views import View from .models import Candidats, Recruteurs # Create your views here. def sign_up_candidat(request): if request.method == "POST": nom = request.POST.get('nom') prenom = request.POST.get('prenom') date = request.POST.get('date') sexe = request.POST.get('sexe') telephone = request.POST.get('telephone') email = request.POST.get('email') password = request.POST.get('pass') password_c = request.POST.get('pass_c') if password != password_c: return HttpResponse("Confirmation password went wrong") else: my_user = Candidats(nomcandidat=nom, prenomcandidat=prenom, datenaissance=date, sexe=sexe, … -
Is there anyway to activate 'venv' on Pycharm?
**Hello i'm using pycharm for Django on windows and when i use this code .\venv\Scripts\activate system shows me this error this is my error what should i do to activating my virtual enviroment ** i just try this code .\venv\Scripts\activate -
How to properly extend user model in Django
I am working on a Django employee management system, I want the employee bio data on the same table as the user object used for registration and login I tried adding the user model as a OnetoOneField on the employee table, but I don’t like having to register the user and then fill the employee form separately. I want the users to be able to create their bio data while creating an account -
Trying to retrieve array from django QueryDict
I want to transfer an array from an Inertia form array to django. In the debug window it's shown as test[0] = 1, test[1] = 2. Neither calling request.POST.get("test") nor request.POST.getlist("test") nor request.POST.getlist("test[]") returns me a usable list. My form object looks as follows (data is hard coded for test purposes): let form = useForm({ "test": [1, 2, 3] }) -
I'm trying to deploy a django site on a hosting. But I don't have SSH access. Are there any other options to do this? [closed]
Я пытаюсь задеплоить сайт на джанго на хостинг. Но у меня нет доступа к SSH. Есть какие нибудь другие способы это сделать? How to deploy django project on host without usinng SSH? Я пытался через wsgi/ htaccess. Но что то не получилось ничего -
psql Cannot open extension control file, but the file exists
psql command line: postgres=# CREATE EXTENSION pg_tgrm; ERROR: extension "pg_tgrm" is not available DETAIL: Could not open extension control file "C:/Program Files/PostgreSQL/15/share/extension/pg_tgrm.control": No such file or directory. HINT: The extension must first be installed on the system where PostgreSQL is running. postgres=# yum install postgresql14-contrib postgres-# CREATE EXTENSION pg_tgrm; The directory: enter image description here What am I doing wrong? The file is definately there and I've installed it on another postgresql server just beforehand on the same machine? This is for a Django project on Windows 11. Tried to install the pg_tgrm; extension and expected it to work. -
Cannot import models into view.py
I have following models.py and views.py . I am trying to change the date to workweek in views file. But when i try to import date , I get the following error: NameError at / name 'date' is not defined Any idea why ?? and how to fix it ?? ---------models.py--------------->> class metric(models.Model): metric = models.CharField(max_length=200) date = models.DateField() value = models.FloatField() goal = models.FloatField() Mowner = models.CharField(max_length=200) ---------views.py ---------------->> from dashboard.models import * from .models import metric import pandas as pd from plotly.offline import plot import plotly.express as px from datetime import datetime def index(request): # Convert date to workweek weeks = [] for date_str in date: date_obj = datetime.strptime(date_str, '%d-%m-%Y') week_num = date_obj.isocalendar()[1] weeks.append(week_num) I tried importing the metrics in views.py file in different ways but still doesnot seem to work . -
How to set a rate limit a specific query in Django?
I have a multithreading function that looks up and locks each item in a list. (I'm locking the query for each individual item so that other users can't hit it at the same time). I also want to limit the rate in which users can look up a specific item, i.e. item1 was just searched so I don't want anyone else to be able to query item1 for 3 minutes. def worker(): """ Item search Multithreading Function """ while True: item = q.get() try: with transaction.atomic(): """ Lock the API for specified item search """ locked = Models.objects.filter(name__icontains=item)[0] locked_search = Models.objects.select_for_update().get(pk=locked.pk) print("Search for " + str(locked_search) + ", " + str(item) + " is locked") ### ADD SERVER RATE LIMIT FOR ITEM SEARCHED HERE ### # ... Do work here I've looked into Django Throttling and django-ratelimit but can't seem to find anything that limits the query rate of particular object. Anyone have any experience in this? Thank you for your help -
Django running function every minutes even without request
I want to write a web application with django. The user choose a specific function (which is defined by developer) and gives the necessary arguments and a frequency (e.g. every 1 minute). Now Django should call the function every 1 minutes and save the required output in database. So I want to ask how can I do scheduling using Django? I heard something about Celery. However, I'm looking for an easier solution. I don't want to end up with queue and messaging concepts! -
Creating multiple objects in DRF failing with error "'int' object has no attribute 'pk'"
I use ListCreateAPIView to create new instances of the Review model. Running my code in debug mode I can see that once the line serializer.is_valid(raise_exception=True) is executed, the code fails with the error AttributeError: 'int' object has no attribute 'pk'. models.py class App(models.Model): name = models.CharField(max_length=200, unique=True) identifier = models.CharField(max_length=200, unique=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) image_url = models.URLField(blank=True, null=True) image_file = models.ImageField( upload_to='images/app_icons/', blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): """ Custom save method which fetches the image_file from the image_url, if image_file does not exist """ if self.image_url and not self.image_file: image = urllib.request.urlopen(self.image_url).read() self.image_file.save(self.name + '.jpg', ContentFile(image), save=False) super().save(*args, **kwargs) class Review(models.Model): comment = models.TextField() rating = models.IntegerField( validators=[MinValueValidator(1), MaxValueValidator(5)]) review_id = models.IntegerField(unique=True) review_date = models.DateTimeField() review_author = models.CharField(max_length=200) app = models.ForeignKey( App, on_delete=models.CASCADE, related_name='reviews') serializers.py class ReviewListSerializer(serializers.ListSerializer): def create(self, validated_data): items = [Review(**item) for item in validated_data] return Review.objects.bulk_create(items) class ReviewSerializer(serializers.ModelSerializer): class Meta: model = Review fields = '__all__' list_serializer_class = ReviewListSerializer views.py class ReviewList(generics.ListCreateAPIView): """Retrieves lists of reviews and creates new reviews Default list method is modified to: - Return count of data under key 'count' """ queryset = Review.objects.all() serializer_class = ReviewSerializer def create(self, request, *args, **kwargs): data = request.data … -
Django CBV with DropzoneJS and django-storages backend for multifile upload form won't validate
I am using django-storages with (GCS backend) and would like to be able to use DropZonejs to upload multiple files to a model that has a FK. This is where I've gotten so far. It always comes back what Bad Request, form not valid. Assuming you're getting to this view from a detail view that includes a pk for 'thing'. (the backend works just fine uploading through django admin) Models.py class Thing(models.Model): name = models.CharField(max_length=25, verbose_name="name") def image_dir_path(instance, filename): # specify file naming return 'folder/{}/{}'.format(instance.thing, filename) class Image(MetadataFields): thing = models.ForeignKey(Thing, on_delete=models.DO_NOTHING, related_name="things", verbose_name=_("Thing")) my_image = models.ImageField(upload_to=image_dir_path, null=True, blank=True, verbose_name=_("My image")) Forms.py class ImageForm(forms.ModelForm): class Meta: model = Image fields = '__all__' widgets = { 'my_image': forms.ClearableFileInput( attrs={'multiple': True}), } Views.py class ImageUploadView(FormView): form_class = ImageForm template_name = "appname/_uploadimages.html" def post(self, request, *args, **kwargs): form_class = self.get_form_class() form = self.get_form(form_class) files = request.FILES.getlist('file') # thing= self.kwargs.get('pk') if form.is_valid(): for uploaded_image in files: # image = models.Image.objects.create(thing=thing, my_image=uploaded_image) image = models.Image() image.my_image = uploaded_image thing_instance= models.Thing.objects.get(id=self.kwargs.get('pk')) image.thing= thing_instance image.save() return HttpResponse('Image upload succeeded.') return HttpResponseBadRequest("Image upload form not valid.") Urls.py path('thing_detail/<int:pk>/view/', views.ThingDetail.as_view(), name='thing_detail'), path('thing/<int:pk>/image/upload/', views.ImageUploadView.as_view(), name='image_upload'), _uploadimages.html {% load static %} <!doctype html> <html lang="en"> <head> <!-- Required meta tags --> … -
Field id expected a number but got <Cart: John's cart>
I have this view I would like to create a cart or update the entries if the cart is already created and if a product is already in the cart then just update its quantity. I am getting an error saying Field id expected a number but got <Cart: John's cart>. Why is the id field even mentioned when I specifically put cart to filter, because I do not have the id of the Entry class CreateCart(generics.CreateAPIView): permission_classes = [permissions.IsAuthenticated] serializer_class = CartSerializer def post(self, request): user = User.objects.get(id=request.data.get("user")) total = request.data.get("carttotal") usercart = Cart.objects.update_or_create(user=user, cart_total=total) products = request.data.getlist("products") for product in products: obj = json.loads(product) id = obj.get("id") qty = obj.get("qty") product = Product.objects.get(id=id) exists = Entry.objects.all().filter(cart=usercart, product=product) if exists: exists.quantity = qty else: Entry.objects.create(product=product, cart=usercart, quantity=qty) return Response("Items added or updated", status=HTTP_201_CREATED) This line Django is complaining about: exists = Entry.objects.all().filter(cart=usercart, product=product) -
Problem with tags in Django | used taggit for storing tags
<div id="tab-2" class="tab-pane fade show p-0"> {% for event in events %} {% for tag in event.tags.all %} {% if tag == 'Tech' %} <div class="row g-3"> <div class="col mb-5"> <div class="d-flex h-100"> <div class="flex-shrink-0"> <img class="img-fluid" src="{{event.e_image.url}}" alt="" style="width: 430px; height: 350px;"> <h4 class="bg-dark text-primary p-2 m-0">{{event.e_date}}</h4> </div> <div class="d-flex flex-column justify-content-center text-start bg-secondary border-inner px-4"> <h5 class="text-uppercase">{{event.e_name}}</h5> </div> </div> </div> </div> {% endif %} {% endfor %} {% endfor %} </div> class Events(models.Model): event_id = models.AutoField(primary_key=True, max_length=10) user_id = models.ForeignKey(User, on_delete=models.CASCADE) e_name = models.CharField(max_length=50) e_image = models.ImageField(null=True, blank=True, upload_to='eventimg') e_date = models.DateTimeField() e_url = models.URLField(null=True, blank=True) tags = TaggableManager() def __str__(self) -> str: return self.e_name When i try {% if tag == 'Tech'%} to display block only when tag is equal to Tech then its not workin. I mean that Block is not at all visible. There are multiple tags in a single event thus i am looping event.tags.all I already had installed, imported and mentioned taggit in settings Its working properly. But i am stucked in above situation -
raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'is_active' into field
I got this doubt, I'm creating a custom user model in Django and at the moment to apply the migrations, it throws me this error raise FieldError( django.core.exceptions.FieldError: Cannot resolve keyword 'is_active' into field. Choices are: cargo, centro, centro_id, direccion, fecha_nacimiento, id, imagen_perfil, last_login, logentry, nacionalidad, password, profesion, rut, sexo, telefono I share you my code, This is the model class Usuario(AbstractBaseUser): centro = models.ForeignKey(Centro, on_delete=models.CASCADE, verbose_name='Centro o Unidad', blank=True, null=True) telefono = models.CharField(max_length=100, unique=True, verbose_name='Teléfono') rut = models.CharField(max_length=100, unique=True, verbose_name='RUT') profesion = models.CharField(max_length=150, verbose_name='Profesión') cargo = models.CharField(max_length=150, verbose_name='Cargo') nacionalidad = models.CharField(max_length=100, verbose_name='Nacionalidad') sexo = models.CharField(max_length=10, choices=SEXO_CHOICES ,verbose_name='Sexo') fecha_nacimiento = models.DateField(auto_now=False, auto_now_add=False,verbose_name='Fecha de nacimiento', blank=True, null=True) imagen_perfil = models.ImageField(upload_to='perfil/', verbose_name='Imágen de Perfil', max_length='255', blank=True, null=True) direccion = models.CharField(max_length=250, blank=True, null=True, verbose_name='Dirección') objects = UsuarioManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['email', 'nombre'] def __str__(self): return self.first_name def get_email_user(self): return self.email.lower() def save(self, *args, **kwargs): self.email = self.email.lower() return super(Usuario, self).save(*args, **kwargs) def has_perm(self, perm, obj = None): return True def has_module_perms(self, app_label): return True @property def is_staff(self): return self.is_staff This is the serializer class UsuarioSerializer(serializers.ModelSerializer): class Meta: model = Usuario fields = '__all__' extra_kwargs = {'password': {'write_only': True}, 'id': {'read_only': True}} I was searching for a answer in several internet forums -
Abstract class and abastract Unitest
I use Django Rest Framework and I wrote something like this: class Vehicule(ABC): wheel = None roof = None def drive(): use wheel and roof, blabla... class Car(Vehicule): wheel = 4 roof = True class Bike(Vehicule): wheel = 2 roof = False It's working good and I want to write unitest with it.I want to write someting similar: class TestVehicule(ABC): wheel = None roof = None factory = None def test_how_many_wheel(self): self.assertEqual(factory.wheel, self.wheel) def test_is_roof(self): self.assertEqual(factory.roof, self.roof) class TestCar(Vehicule) wheel = 4 roof = True factory = CarFactory class TestBike(Vehicule) wheel = 2 roof = False factory = BikeFactory The goal is to write tests in TestVehicule and inherit in others class change variable and do all the tests with the child variable -
How to send a variable from javascript to html?
I would like to fill a table by data from database. I am developing my project using Django. However, required data are based on select elements (depended select), that why I used java script to get data from database. I was able to get required data with java script: const engineInput = document.getElementById('select_eng') const btnBox = document.getElementById('btn-submit') const aircraftForm = document.getElementById('ac-eng-form') const csrf = document.getElementsByName('csrfmiddlewaretoken') const flighInput = document.getElementById('flights') const tablePrint = document.getElementById('table_with_data') aircraftForm.addEventListener('submit', e=>{ e.preventDefault() console.log('submittted') $.ajax({ type: 'POST', url: '/show-data/', data: { 'csrfmiddlewaretoken': csrf[0].value, 'engine': engineInput.value, 'flights': flighInput.value, }, success: function(response) { console.log(response) tablePrint.innerHTML = response }, error: function(error){ console.log(error) } }) }) Now, I want to transfer data from json response to html as a variable "table". How can I do this? I don't want to fill a table using javascript, instead I want to use template engine. <table> <thead> <tr> <th rowspan="2">Flight</th> <th rowspan="2">Date</th> <th colspan="2">Oil quantity, %</th> <th colspan="2">Oil temperature, %</th> <th rowspan="2">dt, hr</th> <th rowspan="2">Engine FH</th> <th colspan="4">Oil Consumption, Quarts/hr</th> </tr> <tr> <th>Qa</th> <th>Qb</th> <th>Ta</th> <th>Tb</th> <th>QH, raw</th> <th>Average for 10 flights</th> <th>Average for 20 flight</th> <th>Average for 30 flight</th> </tr> </thead> <tbody id="table_with_data"> {% for row in table %} <tr> <td>{{row.Flight_Num}}</td> <td>{{row.Flight_Date}}</td> <td>{{row.Oil_Quantity_Departure}}</td> …