Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
which architecture is good for my mobile Chat app in this situation?
I am developing an android app connecting to django backend. My django server in AWS already has own mysql database. (firebase is used for sns authentication) Now I have to add chat functions to this app. It includes group chatting but probably many users may use 1:1 chatting. My question is which architecture is good for mobile Chat app? Options I am thinking now .. Chat messages are stored in mysql database in AWS, and server notify message by only using FCM(Firebase cloud messaging). All text, image or voice urls would be in payload for FCM. A user can only log in on one device at a time. (If this option has no critical performance issue, I think it is a simple way, because I already have backend with database, and I don’t need to care whether user’s Mobile App is in foreground or background. If App needs to show messages when chatting room(channel) is mounted on screed, otherwise just uses notification tray) Use Firebase Realtime database only for chatting functions. It is real time, but I need to create an additional DB in Firebase, and I am not sure how to handle message when app is in background. Chat … -
Put multiple divs on same line using CSS
I'm currently working with Django, and i'm doing a view, where multiple objects from a list are displayed. Right now, each of those objects is on an own line. But i want to have e.g. 2 on one line, so the list is less long on the page. This is my Code so far: html: {% for plant in plants %} <div class="plant"> <img src="{{plant.icon}}"> <div> <label>{{plant.common_name}}</label> <input type="number" name="percentage"/> </div> </div> {% endfor %} CSS: .plant_beet_form { width: 100%; margin: 0 auto; font-size: 3rem; } .plant div { width: 70%; margin: 0 auto; } .plant input{ margin: 0 auto; width: 100%; font-size: 2.5rem; } .plant img { width: 10rem; height: 10rem; margin-bottom: 1rem; } .plant { width: 30%; margin: 0 auto; margin-bottom: 2rem; } I already tried using display:grid and grid-template-rows: 1fr 1fr, but this didn't work either. Any idea? Thank you -
Is there a way I can follow to add my other django app from my other project to my new project? [duplicate]
Please I need a help on how to attach my other app with my new django app. -
How to fix 'workout_details' object has no attribute '_state' Error
I have a problem with showing a queryset of a specific model in my Gym project. Here is 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(validators=[MinValueValidator(1)],blank=True, null=True) I am trying to showing the Breakdown details of every Exercise, but I got this error after several trials. Here is the urls: urlpatterns = [ path('', home.as_view(), name='home'), path('workout/<int:pk>/', workout_details.as_view(), name='workout'), Here is the views: class home(ListView): model = Workout template_name = 'my_gym/home.html' context_object_name = 'workouts' class workout_details(DetailView): model = Exercise.workout template_name = 'my_gym/start_workout.html' context_object_name = 'exercises' # class workout_details(DetailView): # model = Breakdown # template_name = 'my_gym/start_workout.html' # context_object_name = 'breakdown' Here is the template: {% for excercise in excercises %} {{excercise.name}} {% for b in breakdown %} {{b.repetitions}} {% endfor %} {% 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 … -
Table Buttons to Submit Changelist Form in Django
I currently have the following admin page with a set list_editable fields in my ActivityLogAdmin model. When I click "Save" on the bottom of the admin page, the request.POST data gets submitted to my form. I have the following method under my ActivityLogAdmin class: def get_changelist_form(self, request, **kwargs): return ActivityLogChangeListForm However, I'm trying to add one custom button for each entry in my change list, so when I click it, the POST data should also be passed to a view so I can handle that data. However, I can't seem to pass this request.POST data of when I click the button to the view. Here's my attempt: def approve(self, obj): url = reverse('admin:activity_log_approve', args=[str(obj.id)]) return mark_safe(f'<button name="approve_button" type="submit"><a href="{url}">Approve</a></button>') approve.short_description = 'Edit status' urlpatterns = [ url(r'^(.+)/approve/$', wrap(self.approve_view), name='events_activity_log_approve'), def approve_view(self, request, object_id, extra_context=None): print(request.POST['approve_button']) #Is None :( Tried with request.POST only as well form = ActivityLogChangeListForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect('/panel/events/activitylog') Do you guys know what I'm doing wrong? It's been a loong time since I worked with Django and I've wasted 2 days already on that :( Thanks a lot in advance! -
Django date timed events
I need something like this an employee get from date to date a task if date is happend go back to default like previous task or something. any ideas ?