Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Celery Beat and doesn't work correctly With Django orm
I have configured celery and celery beat in Django and they are working correctly except for one problem, When celery beat picks up my task and hand it to the celery worker, my query inside the task has no result, but when I check it myself it has results, below is my task: @shared_task def remove_expired_pending_task(): call_command("remove_pending") and below is the "remove_pending" command handle method: def handle(self, *args, **options): try: aware = pytz.timezone("Asia/Tehran") min_date = aware.localize(jdatetime.datetime.now() - jdatetime.timedelta(hours=7)) max_date = aware.localize(jdatetime.datetime.now() + jdatetime.timedelta(hours=7)) q = Payment.objects.filter( is_completed=False, date__range=(min_date, max_date) ) c = q.count() q.delete() self.stdout.write( f"{c} pending Payament deleted between\ {min_date.strftime('%Y/%m/%d %H-%M-%S')} | \ {max_date.strftime('%Y/%m/%d %H-%M-%S')}") except Exception as exc: self.stderr.write( f"Exception happend in 'Remove pendings'\n: {exc}") and in the celery.py file after the celery app declaration I added this: @app.on_after_configure.connect def setup_periodic_tasks(sender, **kwargs): sender.add_periodic_task(1000.0, remove_expired_pending_task.s(), name='remove_expired_pendings') as I told, celery find and execute the task, but the query returns empty Queryset, but when I run: python manage.py remove_pending it works and Qeuryset is not empty and delete them successfully. do you know why this happens? thank you. -
Django forloop change template after x element
Hi, I try to achieve custom grid with bootstrap 4 using forloop counter. Unfortunately for me something causes the elements to fall apart. I know Im close to achieve this but I try do this for several hours and still I failed to do this. My code: {% for article in healtharticles %} <div class="col-lg-4 col-md-12 mb-4 mb-lg-0"> <!-- News block --> {% if forloop.counter0 < 1 %} <div> <!-- Featured image --> <div class="bg-image hover-overlay shadow-1-strong ripple rounded-5 mb-4" data-mdb-ripple-color="light"> <img src="https://mdbootstrap.com/img/new/fluid/city/113.jpg" class="img-fluid" /> <a href="#!"> <div class="mask" style="background-color: rgba(251, 251, 251, 0.15);"></div> </a> </div> <!-- Article data --> <div class="row mb-3"> <div class="col-6"> <a href="" class="text-info"> <i class="fas fa-plane"></i> Travels </a> </div> <div class="col-6 text-end"> <u> 15.07.2020</u> </div> </div> <!-- Article title and description --> <a href="" class="text-dark"> <h5>This is title of the news</h5> <p> Lorem ipsum dolor sit amet consectetur adipisicing elit. Odit, iste aliquid. Sed id nihil magni, sint vero provident esse numquam perferendis ducimus dicta adipisci iusto nam temporibus modi animi laboriosam? </p> </a> {% else %} <hr /> <!-- News --> <a href="" class="text-dark"> <div class="row mb-4 border-bottom pb-2"> <div class="col-3"> <img src="https://mdbootstrap.com/img/new/standard/city/041.jpg" class="img-fluid shadow-1-strong rounded" alt="" /> </div> <div class="col-9"> <p class="mb-2"><strong>Lorem ipsum … -
How can I compare two dates in the database so that the next one starts with the previous one?
I have model "Education" where the user must enter the years of study at the university. So I just wanna that when the user adds the year of the beginning of studing, the year of the end of studing cannot be lower than the year of the beginning of studing and must be within +10 years from the year of the beginning of studing. Now my models looks like that: My models: def current_year(): return datetime.date.today().year def max_value_current_year(value): return MaxValueValidator(current_year())(value) class Education(models.Model): name_university=models.CharField('University',max_length=300, blank=True) degree_of_edu=models.CharField('Degree of Education', max_length=25, blank=True) start_year=models.IntegerField('Start year',default=current_year(), validators=[MinValueValidator(1945), max_value_current_year]) end_year=models.IntegerField('End year', default=current_year()+1,validators=[MinValueValidator(1945), MaxValueValidator(2100)]) speciality=models.CharField('Speciality', default='Engineer', max_length=250, blank=True) def __str__(self): return '{}'.format(self.name_university) I have understood that IntegerFields can't compere with each other, because i have gotten an error already like this: '>' not supported between instances of 'int' and 'IntegerField' So for example: if u choosed or wrote: 2021, u would able to choose the end of studing only 2022-2031 Or is it possible to do this at all only at the form stage? -
Why am I very-occasionally getting an ImportError using django-constance?
Once every few hundred thousand requests I see one of these: ImportError at / cannot import name 'Config' from partially initialized module 'constance.base' (most likely due to a circular import) (/usr/local/lib/python3.9/site-packages/constance/base.py) I cannot identify any rhyme or reason. It doesn't correspond with accessing constance admin, just randomly occurs. My best guess is it's something to do with the LazyObject in constance's __init__.py, and maybe random race-conditions in restarting expired gunicorn workers or something?! I'm using: Python 3.9.2 Django 3.2 django-constance = {extras = ["database"],version = "==2.8.*"} "constance" and "constance.backends.database" in INSTALLED_APPS (at top) CONSTANCE_BACKEND = "constance.backends.database.DatabaseBackend" "constance.context_processors.config" in TEMPLATES[0]["OPTIONS"]["context_processors"] All my code does is from constance import config and access config attributes in the standard way in python code and Django templates. For what it's worth, we've been using django-constance on this site for years, but never saw this error until we upgraded to 2.8.0 (from 2.6.0). We were using Django 3.1 when it first appeared, but has also occurred since upgrading to 3.2. I cannot find any similar error reports on https://github.com/jazzband/django-constance/ Any ideas what could be causing this and how to resolve it? -
Django and bootstrap contact form not working
I'm trying to make a Django contact form with bootstrap styles, but it's not working. I tried in the views with send_mail instead of EmailMessage but still not work. When I click on the "Send" button, the page just get reloaded and nothing more happens, I don't get any email. Note that I have changed the email address and password for security purposes but it is a gmail account. Here are my files: home.html <footer class="bg-dark text-white pt-3" id="contact"> <div class="row text-center col-lg-12"> <div> <h3>Contact</h3> <img src="{% static 'home_app/img/contact.png' %}" class="img-fluid"> </div> </div> <div class="col-lg-12 mx-auto"> <form method="post"> {% csrf_token %} <div class="row"> <div class="col-lg-6 col-sm-3" > <input type="text" class="form-control" name="name" placeholder="Name and last name" required> </div> <div class="col-lg-6 col-sm-3"> <input type="tel" class="form-control" name="subject" placeholder="Subject" required> </div> <div class="col-lg-12 col-sm-6"> <input type="text" class="form-control" name="email" placeholder="email@example.com" required> </div> <div class="col-lg-12 col-sm-6"> <textarea class="form-control" name="text" placeholder="Write your message" rows="5"></textarea> </div> <div class="col-lg-12"> <button type="Submit" class="btn btn-primary w-100 fs-5">Send</button> </div> </div> </form> </div> </footer> views.py from django.http import HttpResponse from django.shortcuts import render, redirect from django.core.mail import send_mail def contact(request): if request.method == "POST": name = request.POST.get('name') subject = request.POST.get('subject') email = request.POST.get('email') message = request.POST.get('text') return redirect('contact') email=EmailMessage("Message from Django", "User: {} … -
Struggling to see the utility of custom Django Model Managers
I do not have any code for this question, so this will be more about the utility of customer Managers, more so than it is an implementation question. I have read the documentation, many blog posts and tried to implement some myself, but I cannot find the utility in Django custom model Managers. I understand that they can help segment code and can help with DRY principles, but I struggle to see how. So this question can be broken down into a few subpoints How does this help with DRY principles? How does this help with code segmentation? What can managers do that views or model methods cannot do? -
Django Queryset over multiple ForeignKeys
I am struggling with building a QuerySet to get all objects belonging to the current logged-in user. The bills are assigned to a Customer, and CustomerUser objects are assigned to the Customer: ┌──────┐ ┌──────────┐ │ Bill │ ───► │ Customer │ └──────┘ FK └──────────┘ ▲ │ │ FK ┌──────────────┐ │ CustomerUser │ └──────────────┘ │ │ FK ▼ ┌──────────────────────────┐ │ contrib.auth.models.User │ └──────────────────────────┘ Models: class Bill(models.Model): date = models.DateField(blank=False) total = models.FloatField(blank=False, null=False, default=0.0) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) class Customer(models.Model): name = models.CharField(max_length=25, blank=False, null=False) class CustomerUser(models.Model): first_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30, blank=True, null=True) user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) Basically I want to craft a QuerySet that returns the Bill objects the CustomerUser has access to. Can this be done with a single QuerySet? -
How can I show all users except an user who is currently logged in using Django
I am trying to show all users but i dont want to show the user who is logged in. This is what i tried: def get_home_page_url(request): user = User.objects.all() h = User.objects.get(id=pk) print(h) # filtered_user = User.objects.filter(id=request.user).exclude(id=request.user) # print("ALL USERS:" + str(filtered_user)) args = { 'user': user, # 'filtered_user': } return render(request, 'home.html', args) I tried these but I am getting error and error. -
Django translation manager path issue in Heroku
I used Django with translate manger and it works normally in my local host. When I deployed it to Heroku, then translation function is not worked. The code is settings.py: PROJECT_ROOT = os.path.dirname(os.path.realpath(__name__)) LOCALE_PATHS = ( os.path.join(PROJECT_ROOT, 'locale'), ) Then I tried to makemessages in Heroku File "/app/.heroku/python/lib/python3.9/site-packages/translation_manager/management/commands/makemessages.py", line 70, in handle os.chdir(get_settings('TRANSLATIONS_PROJECT_BASE_DIR')) FileNotFoundError: [Errno 2] No such file or directory: '' How can I fixed this issue? -
Change drf action url
I have an action on a viewset. The action name is image, is it possible to make url like path/to/api-point/3/image.jpg instead of path/to/api-point/3/image. -
Python update inherited dictionary
I have class class Base: filters = { 'today': '__today' } and another class class Filter(Base): new_filters = { 'yesterday': '__yesterday' } filters = {**self.filter, **new_filter} You may see the filter class above, I tried to add an additional key but it doesn't seem to work, Can anyone tell me what is the best way to do it? -
How to restrict view in Django from other users?
I am trying to make a page that only can be seen by the user for who the results belongs to. So I like to make that only the user with user_name_id=1 (and the superuser) could see the page that is localhost:8000/mpa/sum/1/ I tried in the html this: {% if request.user.is_superuser %} <div class="container text-justify p-5"> <div class="display-4 text-left text-primary my-3"> ... {% else %} You are not able to view this page! {% endif %} This works fine with the superuser but how could I do this with the users? views.py @login_required def individual_sum(request, user_name_id): ... lots of query context = { ... lots of contexts } return render(request, 'stressz/individual_sum.html', context) models.py class IndividualSum_text(models.Model): def __str__(self): return str(self.user_name) user_name = models.ForeignKey(User, on_delete=models.CASCADE, default=1) ...integerfields and textfields here -
Does anyone have experience working as a developer in Austria? [closed]
Is anyone here that works as a software developer in Austria? I had a job offer and I need some details. -
Django CreateView not creating a new user from 3 related models through ModelForm
I've created models in a Django project, one of which is an extended User model. Initially, I was creating a user through 2 forms, UserCreationForm and EmployeeForm based of a ModelForm, then using a function based view to validate the data and save it. It all worked fine until I tried to introduce the third form and wanted to use the CreateView. Here are the models: class Employee(models.Model): SENIOR = 'Sr' JUNIOR = 'Jr' FIRST = 'I' SECOND = 'II' THIRD = 'III' GENERATIONAL_SUFFIX = [ (SENIOR, 'Senior'), (JUNIOR, 'Junior'), (FIRST, 'First'), (SECOND, 'Second'), (THIRD, 'Third'), ] MALE = 'male' FEMALE = 'female' OTHER = 'other' SEX = [ (MALE, 'Male'), (FEMALE, 'Female'), (OTHER, 'Other'), ] user = models.OneToOneField(User, on_delete=models.CASCADE) phone_regex = RegexValidator(regex=r'^\d{11}$', message="Phone number must be entered in the format: '09151234567'.") phone_number = models.CharField(validators=[phone_regex], max_length=11, blank=True) middle_name = models.CharField(max_length=20, blank=True) sex = models.CharField(max_length=6, choices=SEX, blank=True) suffix = models.CharField(max_length=3, choices=GENERATIONAL_SUFFIX, blank=True) birthday = models.DateField(null=True, blank=True) hire_date = models.DateField(null=True, blank=True) image = models.ImageField(blank=True, default='blank_profile_picture.jpg') slug = models.SlugField(max_length=60, blank=True, null=True) updated = models.DateTimeField(auto_now=True) @property def get_full_name(self): first_name = self.user.first_name middle_name = self.middle_name last_name = self.user.last_name if middle_name is None: full_name = f'{first_name}{" "}{last_name}' return full_name else: full_name = f'{first_name}{" "}{middle_name}{" "}{last_name}' return … -
Django annotate sum on fk_set
I'm trying to annotate sum of fields in related set: My models: class Report(models.Model): class ReportCommissionPosition(models.Model): report = models.ForeignKey(Report) reservation = models.OneToOneField("reservations.Reservation") class Reservation(models.Model): class Payment(models.Model): amount = models.DecimalField(max_digits=10, decimal_places=2) reservation = models.ForeignKey('reservations.Reservation') PAYMENT_TYPES=( ('TRANS', 'TRANS'), ('SELL', 'SELL'), payment_accounting_type = models.CharField(max_length=50, choices=PAYMENT_TYPES) I need to annotate each position of report.reportcommissionposition_set with two fields: trans_amount - Sum of all the payments with payment accounting type == 'SELL' (through reservation => payment) sum_amount - Sum of all the payments with payment accounting type == 'TRANSFER' (through reservation => payment) I have tried: for position in commission_position: position.sell_pay = position.reservation.payment_set.filter(payment_accounting_type='SELL').aggregate(amount=Sum('amount'))['amount'] But this creates new query for every element. Any thoughts? -
I don't know why my django signup form can't create the new user
I made a signup form and a signup view in the Django project. But it seems that 'create_user' does not work. There is no error. Signup view just sends the browser to Home without creating a new user object The user model is using email as a username. I tried to do this with ModelForms but it was the same. I don't know why happens this. users/forms.py class StudentSignUpForm(forms.Form): first_name = forms.CharField() last_name = forms.CharField() email = forms.EmailField( widget=forms.EmailInput(attrs={"placeholder": "Enter your emaill adress"}) ) password = forms.CharField( widget=forms.PasswordInput(attrs={"placeholder": "Enter the Password"}) ) password_confirm = forms.CharField( widget=forms.PasswordInput(attrs={"placeholder": "Confirm the Password"}) ) def clean_email(self): email = self.cleaned_data.get("email") try: models.User.objects.get(email=email) raise forms.ValidationError("This email already exists.") except models.User.DoesNotExist: return email def clean_password_confirm(self): password = self.cleaned_data.get("password") password_confirm = self.cleaned_data.get("password_confirm") if password != password_confirm: raise forms.ValidationError("Password confirmation does not match.") else: return password def save(self): first_name = self.cleaned_data.get("first_name") last_name = self.cleaned_data.get("last_name") email = self.cleaned_data.get("email") password = self.cleaned_data.get("password") user = models.User.objects.create_user(email, password) user.first_name = first_name user.last_name = last_name user.save() users/views.py class StudentSignupView(FormView): template_name = "users/student_signup.html" form_class = forms.StudentSignUpForm success_url = reverse_lazy("core:home") def form_vaild(self, form): form.save() email = form.cleaned_data.get("email") password = form.cleaned_data.get("password") user = authenticate(self.request, username=email, password=password) if user is not None: login(self.request, user) return super().form_valid(form) templates/users/student_signup.html {% … -
How can I pass dictionary in Django Rest Framework?
In django, I was able to pass data using dictionary. Like I set the objects in my dictionary and pass it in return render and call the object in frontend (return render(request, 'c.html', context) right? so How can I do this in django rest? -
django-notifs raising an exception: django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp'
I'm trying to apply Notifications system to my django (version 3.2) app for the first time using the tutorial: https://django-notifs.readthedocs.io/en/stable/index.html# I'm stuck at the installation process. First I solved the (fields.E180) SQLite does not support JSONFields. After running makemigrations, it worked fine. BUT after running manage.py migrate, it threw the following error: raise FieldDoesNotExist("%s has no field named '%s'" % (self.object_name, field_name)) django.core.exceptions.FieldDoesNotExist: Notification has no field named 'timestamp'. Please help me out :( -
Django application with Apache and mod_wsgi on Windows server:
Added this to my windows server httpd.conf: LoadFile "c:/users/rootadmin/appdata/local/programs/python/python39/python39.dll" LoadModule wsgi_module "c:/users/rootadmin/appdata/local/programs/python/python39/lib/site-packages/mod_wsgi/server/mod_wsgi.cp39-win_amd64.pyd" WSGIPythonHome "c:/users/rootadmin/appdata/local/programs/python/python39" WSGIPythonPath "C:/Users/rootadmin/DSS_code/tdid/DSS/" <VirtualHost *:80> WSGIScriptAlias / C:/Users/rootadmin/DSS_code/tdid/DSS/DSS/wsgi.py <Directory "C:/Users/rootadmin/DSS_code/tdid/DSS/DSS"> Require all granted Alias /static "C:/Users/rootadmin/DSS_code/tdid/DSS/static" <Directory "C:/Users/rootadmin/DSS_code/tdid/DSS/static"> Require all granted When trying to run apache getting following error in error log: AH00418: Parent: Created child process 4596 Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\Apache24\bin\httpd.exe' sys.base_prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.base_exec_prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.platlibdir = 'lib' sys.executable = 'C:\Apache24\bin\httpd.exe' sys.prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.exec_prefix = 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39' sys.path = [ 'C:\Users\rootadmin\AppData\Local\Programs\Python\Python39\python39.zip', '.\DLLs', '.\lib', 'C:\Apache24\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00001200 (most recent call first): [Sat Aug 28 04:19:40.123798 2021] [mpm_winnt:crit] [pid 2312:tid 600] AH00419: master_main: create child process failed. I have been digging around but nothing has worked so far. Any suggestions ? -
502 Bad Gateway in django app on vps why?
I am trying to deploy a django project but i get 502 Bad Gateway [i used this tutorial https://dev.to/ndemo/how-i-deployed-my-django-app-to-vultr-vps-3k1i][1] i used supervisor , guncorn and nginx ./virtualenvs/legaland_env/bin/gunicorn #!/bin/bash NAME="django_project" DIR=/home/django/django_project USER=django GROUP=django WORKERS=3 BIND=unix:/home/django/run/gunicorn.sock DJANGO_SETTINGS_MODULE=django_project.settings DJANGO_WSGI_MODULE=django_project.wsgi LOG_LEVEL=error cd $DIR source ../bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DIR:$PYTHONPATH exec ../bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $WORKERS \ --user=$USER \ --group=$GROUP \ --bind=$BIND \ --log-level=$LOG_LEVEL \ --log-file=- /etc/supervisor/conf.d/sqh.conf [program:sqh] startsecs=0 command=/home/admin/legaland/virtualenvs/legaland_env/bin/gunicorn user=admin autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/admin/legaland/gunicorn-error.log /etc/nginx/sites-available/sqh upstream app_server { server unix:/home/admin/legaland/run/gunicorn.sock fail_timeout=0; } server { listen 80; # add here the ip address of your server # or a domain pointing to that ip (like example.com or www.example.com) server_name ; keepalive_timeout 5; client_max_body_size 4G; access_log /home/admin/legaland/logs/nginx-access.log; error_log /home/admin/legaland/logs/nginx-error.log; location /static/ { alias /home/admin/legaland/Legaland/src/static_root/; } # checks for static file, if not found proxy to app location / { try_files $uri @proxy_to_app; } location @proxy_to_app { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://app_server; } } -
how to change http to https in django
If you continue to load with http from a site that can be accessed with https, the process is still alive, but you cannot enter the screen. For this I also clear the cache and turn off the pc, but the same thing happens. I ran Django with python manage.py runsslserver --certificate django.crt --key django.key. For this I set secure_ssl_redirect to true in settings.py to change http to https, but to no avail. Also, when I created a new Django project and ran it on the same server, this problem did not occur. Please help me. I've been wandering around for 2 weeks. -
Django - Getting an object from an obeject
Views: class Book_PrommotionViewSet(viewsets.ViewSet): def list(self, request): queryset = Prommotion.objects.filter(active=True) serializer = PrommotionSerializer(queryset, many=True) return Response(serializer.data, HTTP_200_OK) Prommotion Model: class Prommotion(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) precent = models.DecimalField(decimal_places=2, max_digits=255, null=True, blank=True) active = models.BooleanField(default=False) date_from = models.DateField() date_to = models.DateField() book = models.ForeignKey(Book, on_delete=models.SET_NULL, null=True, blank=True) country = models.ForeignKey(Country, on_delete=models.SET_NULL, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: verbose_name = 'Prommotion' verbose_name_plural = 'Prommotions' Book Model: class Book(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) title = models.CharField(max_length=255, null=True, blank=True) author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True, blank=True) price = models.DecimalField(decimal_places=2, max_digits=255) published = models.DateField() edition = models.CharField(max_length=255) isbn_code = models.CharField(max_length=255) pages = models.IntegerField(blank=True, null=True, default=0) description = models.TextField(null=True, blank=True) cover = models.CharField(max_length=30, choices=Cover.choices(), default=None, null=True, blank=True) genre = models.CharField(max_length=30, choices=Genre.choices(), default=None, null=True, blank=True) language = models.CharField(max_length=30, choices=Language.choices(), default=None, null=True, blank=True) format = models.CharField(max_length=30, choices=Format.choices(), default=None, null=True, blank=True) publisher = models.CharField(max_length=30, choices=Publisher.choices(), default=None, null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: verbose_name = 'Book' verbose_name_plural = 'Books' So, im trying to get the object "Book" from prommotion. Book is a ForeignKey in "prommotion" and i filtered all the prommotions that are active. And i need to get the "Book" object from the Prommotion if its active … -
Is there a Django Graphql Generator?
I am wondering if there a way to automatically generate graphql queries and mutations in Django applications. Using Ariadne + Django + Python 3.9 system i created is here: https://github.com/bastianhilton/Alternate-CMS -
Django sum values of from a for loop in template
I want to show the sum for the values (cals, protein, carbs, etc) of multiple foods in a new table but have no idea how to do it in a django template. Heres what the for loop displays {% for food in meal.foods.all %} <div class='table-container'> <table class='food-table'> <thead> <tr> <th>Name</th> <th>Calories</th> <th>Protein</th> <th>Carbs</th> <th>Fat</th> <th>Sugar</th> <th>Sodium</th> </tr> </thead> <tbody> <tr> <td>{{ food.name }}</td> <td>{{ food.calories }}</td> <td>{{ food.protein }}g</td> <td>{{ food.carbs }}g</td> <td>{{ food.fat }}g</td> <td>{{ food.sugar }}g</td> <td>{{ food.sodium }}mg</td> </tr> </tbody> </table> </div> {% endfor %} The new table would look like this but just display the totals. -
How do I create a delete button in the Image field?
I'm new to programming and I'm taking my first steps, especially in django, in this case I used ImageField to upload images on the site I'm programming, but it only shows the path of the image and I was wondering how I could add a delete button to the page to edit a post...enter image description here enter image description here