Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how i can show django proxy model to a virtual app
I create a proxy model from orginal model Product. How I can show this proxy model to another virtual app called "Store2" class ProductProxy(models.Product): class Meta: proxy = True @admin.register(ProductProxy) class HeroProxyAdmin(admin.ModelAdmin): list_display = ['id'] @admin.register(models.Product) class ProductProxyAdmin(admin.ModelAdmin): list_display = ['id', 'title' -
How to delete all records which is 24 hours old using django ORM?
Model class Question(models.Model): question_text = models.CharField(max_length=100) option1 = models.CharField(max_length=50,null=False) option1_vote = models.IntegerField(default=0) option2 = models.CharField(max_length=50,null=False) option2_vote = models.IntegerField(default=0) option3 = models.CharField(max_length=50,null=False) option3_vote = models.IntegerField(default=0) option4 = models.CharField(max_length=50,null=False) option4_vote = models.IntegerField(default=0) date_time = models.DateTimeField(auto_now=True) user = models.ForeignKey(User,on_delete=models.CASCADE) We have the date_time field here. Question.objects.filter(condition).delete() what condition should I put there? -
How to fix delete record after some date in django not working?
I am trying to delete records after expiry_date_time is less than or equal to current date time but it was not working properly. Also giving this error RuntimeWarning: DateTimeField Question.date_time received a naive datetime (2022-08-28 10:15:19) while time zone support is active. API deleting wrong records. def delete(self, request): count = 0 count, _ = Question.objects.filter( expiry_date_time__lte=datetime.now(timezone.utc).today() .strftime('%Y-%m-%d %H:%M:%S')).delete() print(now().today() .strftime('%Y-%m-%d %H:%M:%S')) resp = {'Total question deleted': count} print(resp) return Response(resp) -
Deploy django restframeworkapi on server
i want to set post req to my api application. in postman when I send the post in the object program, it returns the following text as a response and the data is not saved in the database. i got in browser: Employee List POST /employees/ HTTP 403 Forbidden Allow: GET, POST, HEAD, OPTIONS Content-Type: application/json Vary: Accept { "detail": "CSRF Failed: CSRF token missing or incorrect." } but i got different error in postman: Server Error (500) is set: DEBUG = False ALLOWED_HOSTS = ['*'] in settings.py But the problem is still not solved and the error remains. What should I do to fix this error? -
Can't display object properties when retrieving an Item List
sorry if this is a simple mistake but I couldn't figure it out. I am trying to display the watchlisted items of the logged in user. I am able to display a list but the item details such as title, price etc. don't show up. models.py: class Watchlist(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, name = "user") item = models.ForeignKey(AuctionItem, on_delete = models.CASCADE, name = "item") def __str__(self): return f"Username: {self.user} / {self.item} " views.py: @login_required def watchlist(request,user): user = request.user item_list = Watchlist.objects.filter(user_id=user) return render(request, "auctions/watchlist.html",{ "item_list" : item_list }) watchlist.html: {% extends "auctions/layout.html" %} {% block body %} {% for item in item_list %} <div class = "frame"> {% if item.image %} <img src="{{item.image}}" style= "width: 30vw;"> {% endif %} <h4><a href="{% url 'listing' item.id %}">{{item.title}}</a></h4> <div id="text"><strong>Price:</strong> ${{item.price}}</div> <div id="text"><strong>Description:</strong> {{item.description}}</div> <div id="text"><strong>Category:</strong> {{item.category}}</div><br> <div id="date">Created {{item.date}}</div> </div> {% endfor %} {% endblock %} urls.py: urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create", views.create_listing, name="create"), path("listing/<int:listing_id>", views.listing, name = "listing"), path("<str:user>/watchlist", views.watchlist, name= "watchlist") ] and here is what I'm getting as a result: -
why django returns me a template Error for this case {% if user.is_authenticated %}?
i would like to add on my django template main page interface a condition but it return me this error : ProgrammingError at / relation "django_session" does not exist LINE 1: ...ession_data", "django_session"."expire_date" FROM "django_se... ther is the Template code : ... {% extends '_base.html' %} {% block title %}Home Page{% endblock title %} {% block content %} <h2>Homepage</h2> {% if user.is_authenticated %} <p>Hi {{ user.email }}</p> {% else %} <p>You are not Loged</p> <p><a href="{% url 'login' %}">Log In</a> </p> {% endif %} {% endblock content %} ... thamk you for your answers -
Error with queryset get_absolute_urls Django
django.urls.exceptions.NoReverseMatch: Reverse for 'detail' with keyword arguments '{'slug': 'test'}' not found. 1 pattern(s) tried: ['detail<slug:slug/\\Z'] I'm trying to create a product detail, filtering it by slug(maybe it can be ID), so I decided to send the slug trough an URL and then filter the product by the specifiedslug, but im getting troubles to implement it(my other get_absolute_url its working but this one I cant fix). models.py: class Product(models.Model): name = models.CharField(max_length=255, unique=False, blank=True) slug = models.SlugField(unique=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, unique=False) subcategory = models.ForeignKey( SubCategory, on_delete=models.CASCADE, unique=False, blank=True, null=True) short_description = models.CharField( max_length=255, unique=False, blank=True, null=True) long_description = models.TextField(unique=False, blank=True, null=False) image = models.ImageField(blank=True, null=True, unique=False) on_promotion = models.BooleanField(default=False) def __str__(self): return self.slug def get_absolute_url(self): return reverse("product:detail", kwargs={"slug": self.slug}) urls.py: urlpatterns = [ path('', views.index, name="index"), path('detail<slug:slug/', views.ProductDetail.as_view(), name="detail"), path('category-<int:category_id>/', views.category, name="category"), path('category-<int:category_id>/subcategory-<int:subcategory_id>', views.subcategory, name="subcategory") ] views.py """ def detail(request, product_id): product = Product.objects.get(product_id) return render(request, 'product/detail.html', {'product_id': product}) """ class ProductDetail(DetailView): template_name = 'product/detail.html' # queryset = Product.available.all() def get_queryset(self): queryset = Product.available.filter(slug=self.kwargs.get("slug")) return queryset def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) return context template: <a href="{{product.get_absolute_url}}">aaa</a> -
How can I create a form and view from forms.py?
I have model with AbstractBaseUser and BaseUserManager. I have also build admin.py and forms.py. That all works just fine I checked in admin, so now I want to actually create a form in which user could type in and view which will take that data and create new user. Since there aren't many good tutorials on AbstractBaseUser I don't know how to do that myself. If you want me to post anything else just write in comments:) models.py from multiprocessing.managers import BaseManager from django.db import models from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser ) class UserManager(BaseUserManager): def create_user(self, email, password=None): """ Creates and saves a User with the given email and password. """ if not email: raise ValueError('Users must have an email address') user = self.model( email=self.normalize_email(email), ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self, email, password): """ Creates and saves a staff user with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.save(using=self._db) return user def create_superuser(self, email, password): """ Creates and saves a superuser with the given email and password. """ user = self.create_user( email, password=password, ) user.staff = True user.admin = True user.save(using=self._db) return user class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', … -
Document for django project
How can I write a Document for my project? Does anyone know the correct tutorial? I want to write a document for my Django project. Does anyone know a suitable road map? -
Display ManyToManyField of User which are in request.user profile in drf
I am building a Blog App and with React and Django Rest Framework, and I am trying to display liked field which is ManyToManyField in Profile model, In Django Rest Framework. But the problem is It is showing request.user's username in every item of the response list (in axios data). like :- [{"likes": ["user_1"]},{"likes": ["user_1"]}] models.py class Profile(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) likes = models.ManyToManyField(User, related_name='likes') serialiers.py class LikesSerializer(serializers.ModelSerializer): likes = serializers.StringRelatedField(many=True) class Meta: model = Profile fields = ( "likes", ) views.py class LikesUserApiView(viewsets.ModelViewSet): serialier_class = LikesSerializer def get_queryset(self, *args, **kwargs): return self.request.user.profile.likes.all() I have also by using filter in view, like return Profile.objects.filter(likes=self.request.user) But is showed []. What I am trying to do ? I am trying to get users which are in ManyToManyField of request.user. also tried by using likes__in=self.request.user but it showed TypeError: 'User' object is not iterable. -
Encrypt data in file txt using AES in django
so i want to encrypt data what's in the file i was upload. but when i read the data, the plaintext says it's none (i called that func at func encrypt) but when i called that func at homepage, its works well (can read the data). i don't know what's wrong. please help me to encrypt data in the file txt what i was upload. here's my code: def read_file(f): f = open('media/txt/'+f, 'r') f.read() f.tell() f.seek(0) file_content = f.read() f.close() print(file_content) key_bytes = 16 # here's a rudimentary change that accepts bytes or # str def encrypt(key, pt): plaintext = read_file(pt) # plaintext = plaintext[0] # if isinstance(plaintext, str): # pt= plaintext.encode("utf-8") print(plaintext) assert len(key) == key_bytes # Choose a random, 16-byte IV. iv = Random.new().read(AES.block_size) # Convert the IV to a Python integer. iv_int = int(binascii.hexlify(iv), 16) # Create a new Counter object with IV = iv_int. ctr = Counter.new(AES.block_size * 8, initial_value=iv_int) # Create AES-CTR cipher. aes = AES.new(key.encode('utf8'), AES.MODE_CTR, counter=ctr) # Encrypt and return IV and ciphertext. ciphertext = aes.encrypt(plaintext) print(ciphertext) return (iv, ciphertext) -
Django + Celery - How to send Django's password reset email using Celery?
This question has been answered previously here, but this solution didn't help me, my email is not sent by Celery. I use Celery 5.1.2 My code: forms.py from django.contrib.auth import forms as admin_forms from django.utils.translation import gettext_lazy as _ from users.tasks import reset_password class PwdResetForm(admin_forms.PasswordResetForm): email = forms.EmailField(max_length=150, widget=forms.TextInput()) def clean_email(self): email = self.cleaned_data['email'] test = User.objects.filter(email=email) if not test: raise forms.ValidationError( _('Unfortunately we can not find that email address')) return email def send_mail( self, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name=None, ): context['user'] = context['user'].id reset_password.delay(subject_template_name=subject_template_name, email_template_name=email_template_name, context=context, from_email=from_email, to_email=to_email, html_email_template_name=html_email_template_name) tasks.py from django.contrib.auth import get_user_model from django.contrib.auth.forms import PasswordResetForm from celery import shared_task from config.celery_app import app User = get_user_model() @shared_task # I also tried using @app.task def reset_password(subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name): context['user'] = User.objects.get(pk=context['user']) PasswordResetForm.send_mail( None, subject_template_name, email_template_name, context, from_email, to_email, html_email_template_name ) celery_app.py import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "auto_store.settings") app = Celery("auto_store") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() Maybe this is due to the fact that I also have tasks.py in another app? If it's possible, I want to solve this problem without third-party package. Thanks for the help. -
How to get value from jinja for loop in django
I have a form which contains table where list of students from data base is listed I want to get the value of every student from table on submit button and also there status if they are present or not Html Code <div class="container"> <form method="POST" action="takeattendance"> {% csrf_token %} <div class="form-group"> <h4 style="color:white;"> Select Subject For Attendance</h4> <select class="btn btn-success" name="subject"> <option selected disabled="true">Subject</option> {% for sub in subjects%} <option value="{{ sub.id }}">{{sub.subject_name}}</option> {%endfor%} </select> </div> <table class="table" > <thead> <tr> <th scope="col" style="color:white;"><b>Email</b></th> <th scope="col" style="color:white;"><b>Roll No.</b></th> <th scope="col" style="color:white;"><b>First Name</b></th> <th scope="col" style="color:white;"><b>Last Name</b></th> <th scope="col" style="color:white;"><b>Year</b></th> <th scope="col" style="color:white;"><b>Division</b></th> <th scope="col" style="color:white;"><b>Batch</b></th> <th scope="col" style="color:white;"><b>Attendance</b></th> </tr> </thead> <tbody> {%for student in students%} {%if user.staff.class_coordinator_of == student.division and user.staff.teacher_of_year == student.year%} <tr> <td style="color:white;" name="student_name" value="{{student.id}}">{{student.user}}</td> <td style="color:white;">{{student.roll_no}}</td> <td style="color:white;">{{student.user.first_name}}</td> <td style="color:white;">{{student.user.last_name}}</td> <td style="color:white;">{{student.year}}</td> <td style="color:white;">{{student.division}}</td> <td style="color:white;">{{student.batch}}</td> <td> <div class="form-group"> <select class="btn btn-success" name="status" id="status"> <option selected value="Present">Present</option> <option value="Absent">Absent</option> </select> </div> </td> </tr> {% endif %} {%endfor%} </tbody> </table> <div class="form-group"> <button type="submit" class="btn btn-info btn-lg ">Add</button> </div> </form> </div> views.py def staffattendance(request): if request.user.is_authenticated and request.user.user_type==3: subjects = Subject.objects.all() students=Student.objects.all() return render (request, 'ms/staff/attendance.html',{'subjects':subjects, 'students':students}) else: return render(request,'ms/login/login.html') def takeattendance(request): if request.method == "POST": … -
How to send ImageFieldFile objects fetched from the database by django to the front-end and display them
When using django as a backend, I have an image saved in the database in ImageField format, and in the view layer I get the object via orm, how can I return it to my vue frontend. I turned the ImageField object into a string to return a JsonResponse, but the front-end only gets the name of the image when it's read def getContent(request): mtitle=request.GET.get('title') row_obj=models.content.objects.filter(title=mtitle).first() res={ "pic":str(row_obj.img), } print(type(row_obj.img)) return JsonResponse(res, json_dumps_params={"ensure_ascii": False}) How do I request the image to be displayed on the front end? -
How to use order_by and annotate in Django to retrieve products based on the order of a season?
Assuming I got a Product model. I use Django-taggit to allow me to add tags for each product. In each product I will add tags like winter, summer, autumn, spring. Then I create functions like this_month() using timezone.now for time aware in Django. The this_month() function would return an integer such as 8 for august since I would be using .strftime(). Now I would create a this_season(this_month) function which accepts only an integer; this function would return a string such as 'winter'. So, to sum it up, I can call this_season(this_month) to get the correct season such as if now = timezone.now, this_month = now.strftime('%m'), and season = this_season(this_month) - if this_month is an integer of 8 - then this_season() would return 'summer'. The question is how do I query the database using annotate to create a pseudo column that allows me to retrieve the products that order_by tags (using tags of Django-taggit) based on the season? So, the results would return with products that in the correct season in descending order - meaning the product of the season Summer in August would show at the top of the list. Any clue? -
Cannot display API Json data to display on Django Template
I am trying to get data from a JSON, which was fetched from an API I created to display on my Django Template. The API is just a simple API which store a post hit counts and its id, the json is formatted as below: [ { "object_pk": 3, "hits": 15 }, { "object_pk": 1, "hits": 21 } ] Here is my views.py file: class BlogListView(ListView): model = Post template_name = "home.html" class BlogDetailView(HitCountDetailView, DetailView): model = Post template_name = "post_detail.html" count_hit = True data = { "hits": get_cloudapi_data(), } class ResumePageView(TemplateView): template_name = "resume.html" And my service.py file, which have the get_cloudapi_data() function: def get_cloudapi_data(): url = "my-api-address" r = requests.get(url) hitcount = r.json() return hitcount Below is my HTML template, post_detail.html used for displaying this data: {% extends "base.html" %} {% load hitcount_tags %} {% block content %} <div class="post-entry"> <h2>{{ post.title }}</h2> <p> {% get_hit_count for post %} views</p> <p> {{ post.body }}</p> {% for hit in hits %} <p>{{ hit.object_pk }}</p> <p>{{ hit.hits }}</p> {% endfor %} </div> {% endblock content %} It only shows the title, body and the hit count retrieve with the hitcount app not my API data I have printed out the … -
Django instantiate a file field using model form
I am unable to instantiate a file field from the model form model.py class ModelA(models.Model): image_fileA = ResizedImageField() pdf_fileB = models.FileField() pdf_fileC = models.FileField() forms.py class FormA(ModelForm): class Meta: model = modelA fields = ['image_fileA', 'pdf_fileB', 'pdf_fileC'] widgets = { 'image_fileA': forms.FileInput(), 'pdf_fileB': forms.FileInput(), 'pdf_fileC': forms.FileInput(), } views.py def viewA(request, pk): template = 'app/edit.html' a = modelA.objects.get(id=pk) form = FormA(instance=a) if request.method == 'POST': form = FormA(request.POST, request.FILES, instance=a) if form.is_valid(): form.save() return redirect('page') context = {'a': a, 'form': form, } return render(request, template, context) edit.html <form action="" method="POST" enctype='multipart/form-data'> {% csrf_token %} {%if a.image_fileA%} <img src="{{a.image_fileA.url}}"> {{form.group_logo}} {%else%}Not Available{%endif%} {% if a.pdf_fileB%} <a href="{{a.pdf_fileB.url}}"></a> {{form.pdf_fileB}} {%else%}Not Available{%endif%} {% if a.pdf_fileC%} <a href="{{a.pdf_fileC.url}}"></a> {{form.pdf_fileC}} <button type="submit">Save</button> </form> What I have tried I had to use if else...~~~ to enable file upload in case the file was not available. Have also attached a URL link to enable one to see uploaded files. Errors I expect all fields to have form instances but when i try to save the form without editing I get the following error 'File' object has no attribute 'content_type' Hence the form is only saved when all fields are edited. Can somebody guide where am doing it wrongly. … -
Django url link error Reverse for 'category' with keyword arguments '{'category.id': 1}' not found. 1 pattern
Im trying to create a product filter, filtering it by category, so I decided to send the category id trough an URL and then filter all products by the specified ID, but im getting troubles to implement it, please healp. Reverse for 'category' with keyword arguments '{'category.id': 1}' not found. 1 pattern(s) tried: ['category/<int:category\\.id\\Z'] Views def category(request, category_id): products = Product.objects.filter(category=category_id) return render(request, 'product/category.html', {'products': products}) Model class Category(models.Model): name = models.CharField(max_length=255, unique=False, blank=True) slug = models.SlugField(unique=True) def __str__(self): return self.slug def get_absolute_url(self): return reverse("product:category", kwargs={"category.id": self.id}) Urls urlpatterns = [ path('', views.index, name="index"), path('detail/<int:product_id', views.detail, name="detail"), path('category/<int:category.id', views.category, name="category") ] HTML Template, I tried two ways,none of them worked: {% for category in categories %} {{category.id}} <a href="{{category.get_absolute_url}}"></a> {% comment %} <a href="{% url 'product:category' category_id=category.id %}"></a> {% endcomment %} {% endfor %} Product Model class Product(models.Model): name = models.CharField(max_length=255, unique=False, blank=True) slug = models.SlugField(unique=True) category = models.ForeignKey( Category, on_delete=models.CASCADE, unique=False) -
Django migrations.exceptions.InvalidBasesError (in production)
I run a script with Docker in localhost, there is no problem but when I try to run it in a server, I always get the invalidbase migration error when I run the setup.sh which starts with: python manage.py makemigrations python manage.py migrate ... django.db.migrations.exceptions.InvalidBasesError: Cannot resolve bases for [<ModelState: 'project1.MetaFlatPage'>] This can happen if you are inheriting models from an app with migrations (e.g. contrib.auth) in an app with no migrations; see https://docs.djangoproject.com/en/3.2/topics/migrations/#dependencies for more I run docker compose run web python manage.py makemigrations and output is: "PostgreSQL is up. No changes detected" then run docker compose run web python manage.py makemigrations got the same error above. There are two different docker yml files; dev and production and they are slightly different. I don't know if this relevant but I can share those files too. -
Django Form Disabled Select Option Values Not Submitted Even When They are Enabled with JavaScript Before Submission
My HTML displays about 20 or more forms via modelformset_factory and each having a preselected staff name (so this is disabled in forms.py). Staff name is primary key to Staff model, so I don't want all their names be available for selection. Logged in user have some staff assigned and so they are only required to enter phone number and address. The disabled fields are enabled with Javascript before the form is submitted but I still get {'staff_name': ['This field is required.']} error when the form is submitted. Here are my codes: forms.py class StaffForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['staff_name'].disabled = True views.py class StaffModelFormSet(BaseModelFormSet): def clean(self): super().clean() print(self.errors) class StaffEntryView(LoginRequiredMixin, FormView): def post(self, request, *args, **kwargs): StaffFormSet = modelformset_factory(Staff, form=StaffForm, formset=StaffModelFormSet) submitted_form = StaffFormSet(request.POST) if submitted_form.is_valid(): self.form_valid(submitted_form) print("This form is valid, Sir!") else: self.form_invalid(submitted_form) print("This is not a valid form.") template.html <form method="post" class="form-control" id="staff_form" name="staff-form" onsubmit="enablePath();"> <!-- form details goes here --> <tbody> {% for form in formset %} <tr class="table-striped"> <td>{{ form.staff_name }}</td> <td>{{ form.phone }}</td> <td>{{ form.address }}</td> </tr> {% endfor %} </tbody> script.js function enablePath(e) { var options = document.getElementsByTagName('select'); for (var i=0, iLen=options.length; i<iLen; i++) { options[i].disabled = false; } -
Css is connecting to html but is not rendering correctly
{% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" href="{% static '\css\index.css'%}" /> <title>LUXURY STARTS HERE</title> </head> <body> <section class="content"> <h1>LUXURY VILLAS</h1> <video width="500px" autoplay muted loop src="{% static '\video\production ID_4069480.mp4'%}" ></video> <div class="overlay"></div> <a href="">EXPLORE</a> </section> </body> </html> @import url("https://fonts.googleapis.com/css2?family=Luxurious+Roman&display=swap"); .content { position: absolute; top: 0; right: 0; width: 100%; min-height: 100vh; padding: 0; display: flex; align-items: center; background: gold; font-family: "Luxurious Roman", cursive; z-index: -1; } .content video { position: absolute; width: 100%; height: 80%; object-fit: cover; } .content .overlay { position: absolute; background: black; width: 100%; height: 100%; opacity: 0.5; } .content h1 { font-size: 50px; position: absolute; opacity: 0.7; color: gold; top: 10%; left: 10%; z-index: 1000; } .content a { position: absolute; top: 60%; left: 50%; font-size: 30px; z-index: 1000; text-decoration: none; color: white; width: 5em; font-family: monospace; transition: 0.5s; } .content a:hover { color: gold; letter-spacing: 6px; background: rgb(0, 0, 0); opacity: 0.75; border: 5px solid rgb(0, 0, 0); } Hello I am trying to connect my css to my html but for so on known reason it connects but gives me very weird dark colors. I am trying to … -
How to calculate fees,total and subtracting it from the initial balance in a separate App
VIEWS @login_required(login_url='/login/') def send(request): posts =Transactions.objects.filter(user=request.user) form = TransactionForm() if request.method=="POST": form = TransactionForm(request.POST, request.FILES) if form.is_valid(): form.instance.user=request.user # x=(form.cleaned_data['recipient_sending_amount']) form.save() return redirect('/success/') else: messages.error(request, 'Failed, Resend') context = {'form':form, 'posts':posts} return render(request, 'index_user/send-money.html', context) MODELS class Transactions(models.Model): user = models.ForeignKey(CustomUser,related_name='users',on_delete=models.CASCADE) recipient_account_type = models.CharField(max_length=230) recipient_name = models.CharField(max_length=100) recipient_acount_number = models.PositiveIntegerField() recipient_routing_number = models.PositiveIntegerField() recipient_bank_name = models.CharField(max_length=200) recipient_swift_code = models.CharField(max_length=100) recipient_sending_amount = models.DecimalField(max_digits=15, decimal_places=2) transaction_date = models.DateTimeField(auto_now_add=True) transaction_ID =models.CharField(default=ID,max_length=10) description = models.CharField(max_length=1000) transaction_status = models.CharField(max_length=100, choices=transfer_status, default='COMPLETED') fees =models.IntegerField(default=32,blank=True) total =models.IntegerField(default=0,blank=True) status =models.CharField(max_length=100,choices=status, default='COMPLETED',blank=True) colour =models.CharField(max_length=100,choices=colour, default='Blue',blank=True) FORMS class TransactionForm(forms.ModelForm): class Meta: model = Transactions fields = ['recipient_account_type','recipient_name','recipient_acount_number','recipient_routing_number','recipient_bank_name', 'recipient_swift_code','recipient_sending_amount','description','fees',] I HAVE ANOTHER FIELD IN ACCOUNT APP IN MY CustomUser MODEL NAMED account_balance WHICH I WANT TO SUBSTRACT THE TOTAL FROM -
django foreign key Cannot assign must be a instance error
I have a database with the table cargo_empleado that has an id=1 and cargo_empleado='gerente', I also have an Empleado table, in the Empleado table I want to create an employee, I have a form to create an employee, the employee table has as foreign key cargo_empleado, when I put in the form that the employee belongs to the job id=1, it gives me the error: Cannot assign "'1'": "Empleado.cargo_empleado" must be a "CargoEmpleado" instance. models.py class CargoEmpleado(models.Model): nombre_cargo = models.CharField(max_length=50, blank=True, null=True) class Meta: managed = False db_table = 'Cargo_empleado' class Empleado(models.Model): rut = models.CharField(primary_key=True, max_length=9) nombres = models.CharField(max_length=100, blank=True, null=True) apellidos = models.CharField(max_length=100, blank=True, null=True) correo_electronico = models.CharField(max_length=100, blank=True, null=True) usuario = models.CharField(max_length=50, blank=True, null=True) contrasena = models.CharField(max_length=255, blank=True, null=True) activo = models.IntegerField() cargo_empleado = models.ForeignKey(CargoEmpleado, models.DO_NOTHING, db_column='cargo_empleado') id_empresa = models.ForeignKey('Empresa', models.DO_NOTHING, db_column='id_empresa', blank=True, null=True) id_unida = models.ForeignKey('UnidadInterna', models.DO_NOTHING, db_column='id_unida') class Meta: managed = False db_table = 'Empleado' views.py def crearusuario(request): if request.method=="POST": if request.POST.get('rut') and request.POST.get('nombres') and request.POST.get('apellidos') and request.POST.get('correo_electronico') and request.POST.get('usuario') and request.POST.get('contrasena') and request.POST.get('activo') and request.POST.get('cargo_empleado') and request.POST.get('id_empresa') and request.POST.get('id_unida'): usersave= Empleado() usersave.rut=request.POST.get('rut') usersave.nombres=request.POST.get('nombres') usersave.apellidos=request.POST.get('apellidos') usersave.correo_electronico=request.POST.get('correo_electronico') usersave.usuario=request.POST.get('usuario') usersave.contrasena=request.POST.get('contrasena') usersave.activo=request.POST.get('activo') usersave.cargo_empleado=request.POST.get('cargo_empleado') usersave.id_empresa=request.POST.get('id_empresa') usersave.id_unida=request.POST.get('id_unida') cursor=connection.cursor() cursor.execute("call SP_crear_usuario('"+usersave.rut+"','"+usersave.nombres+"', '"+usersave.apellidos+"', '"+usersave.correo_electronico+"', '"+usersave.usuario+"', '"+usersave.contrasena+"', '"+usersave.activo+"', '"+usersave.cargo_empleado+"', '"+usersave.id_empresa+"', '"+usersave.id_unida+"')") messages.success(request, "El empleado … -
How can I change the background color of a column based on the value of another column
I'm using Django framework. I have a table that contains some columns. I need to change the background of the aht column based on the agent_target column so if the value lower than or equal the target the background should be green, else it should be red. {% for item in data %} <tr> <td class="text-center align-middle">{{ item.loginid }}</td> <td class="text-center align-middle">{{ item.agentname }}</td> <td class="text-center align-middle">{{ item.team }}</td> <td class="text-center align-middle">{{ item.queue_name }}</td> <td class="text-center align-middle">{{ item.sumduration}}</td> <td class="text-center align-middle">{{ item.countduration}}</td> <td class="text-center align-middle aht">{{ item.aht}}</td> <td class="text-center align-middle target">{{ item.agent_target}}</td> </tr> {% endfor %} When I try to access the value of the AHT column using the below js it returns undefined value console.log(document.getElementById("aht").value) -
Adding Context to Class Based View Django Project
I have a problem with showing a queryset of a specific model in my Gym project. I have tried many different query's but none is working the models: class Workout(models.Model): name = models.CharField(max_length = 30,blank=True, null=True) class Exercise(models.Model): workout = models.ForeignKey(Workout, on_delete=models.CASCADE, related_name='exercises',blank=True, null=True) name = models.CharField(max_length = 30, blank=True, null=True) class Breakdown(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, related_name='excercise',blank=True, null=True) repetitions = models.IntegerField() I am trying to showing the repetitions in the Breakdown model which has a ForeignKey relation with Exercise which has a ForeignKey relation with Workout views.py class home(ListView): model = Workout template_name = 'my_gym/home.html' context_object_name = 'workouts' class workout_details(ListView): model = Exercise template_name = 'my_gym/start_workout.html' context_object_name = 'exercises' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['breakdown'] = Exercise.objects.filter(breakdown=self.breakdown) return context urls.py urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), ] template: {% for e in exercises %} {{ e.name }} {{ breakdown.repetitions }} {% endfor %} My question what is my mistake here that is either getting me an error or not showing the required data set. my objective is the choose from the home page a Workout from list and next page to be the list of exercises with the repitions related to it.