Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Preview an image selected with ImageField in Django model form
I made a simple form to upload a picture. It's html looks like this: <div id='article_image_form'> <div id='image_title_form'> <p> Upload your image </p> </div> <div class='upload_image_button'> <div id='upload_image_button_text'> <p> File </p> </div> {{ form.image }} </div> </div> Is there a way to check if a file was selected and show another form with an image preview instead of selection form? -
Django, group objects in query set by date
I have a query set that contains daily farm data. I want to create an average of hours but per day not for the all queryset. So it should look something like this: daily_data = dict() for day in get_last_year_range(): # havn't implemnted this method yet daily_farm_average = GroupDailyData.objects.filter(group__farm='1', group__milking=True, day=day).aggregate( average_daily_hours=Avg('hours')) daily_data.update({day: daily_farm_average['average_daily_hours']}) return daily_data -
User Authentication without page refresh in Django
Is it possible to do user authentication without page refresh or reload just by using Django and not using Django REST framework? -
Django join multiple models in query result
Is it possible to do an equivalent of a LEFT JOIN using django models? Let's assume that I have 3 models: class Post(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=100) date_posted = models.DateTimeField(auto_now_add=True) class Bookmark(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) bookmarked_by = models.ForeignKey(User, on_delete=models.CASCADE) class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE) owner = models.ForeignKey(User, on_delete=models.CASCADE) comment = models.CharField(max_length=100) date_created = models.DateTimeField(auto_now_add=True) # in my DRF view, I want to return: # [ # { # "id": post.pk, # "owner": post.owner, # "title": post.title, # "bookmark_id": bookmark.id, // should be null if current user has not bookmarked the post # "comment_count": total_number_of_comments for this post # }, # ...] class PostView(generics.ListAPIView): def get_queryset(self): current_user = self.request.user I want to return all post, but also include the bookmark id of the post which current user has bookmarked. I am currently using 2 LEFT JOINS to achieve this but I am wondering if there is a django way of getting the same output. -
Is it safe to use unknown Bootstrap CSS link
I am building this website using Django, now I have some prebuild templates which I want to use and they have there existing CSS. But for displaying alert messages I wanted to use bootstrap, so basically I want to isolate bootstrap to a particular div. So I looked up on the internet and found this. Now since it was not provided by bootstrap itself I was curious if I should use this and if it has some security issues or not. Please can you look into it and tell I should be using it or not. -
django-allauth-2fa: Unexpected behaviour of accounts/two_factor/setup/ -> page reload after pressing 'verify'
I am trying to use django-allauth & django-allauth-2fa in my Django app. My django-allauth app is set uo correctly - everything is working as expected. However, when trying to set up django-allauth-2fa I ran into some issues: Configuring a two-factor authentification at accounts/two_factor/setup/ when I scan the QR code, input the token generated and press verify the page simply reloads with a new QR code instead of leading me to the next step in the Two-Factor configuration workflow. I can't figure out what my mistake may be, as I set up everything as written in the django-allauth-2fa documentation My Pipfile: [[source]] name = "pypi" url = "https://pypi.org/simple" verify_ssl = true [dev-packages] [packages] django = "==3.0.0" pylint = "==2.4.4" django-crispy-forms = "==1.9" django-allauth = "==0.42.0" django-allauth-2fa = "==0.8" [requires] python_version = "3.7" my settings.py file: ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', # Local 'users.apps.UsersConfig', 'pages.apps.PagesConfig', #Third-party 'allauth', 'allauth.account', 'django_otp', 'django_otp.plugins.otp_totp', 'django_otp.plugins.otp_static', 'allauth_2fa', 'crispy_forms', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django_otp.middleware.OTPMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'allauth_2fa.middleware.AllauthTwoFactorMiddleware', ] SITE_ID = 1 ACCOUNT_ADAPTER = 'allauth_2fa.adapter.OTPAdapter' ... my urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth_2fa.urls')), path('accounts/', include('allauth.urls')), path('', … -
How should i structure Django Project and form Applications?
I am developing a blogging site. I need help in structuring the django applications. Features i have are: Blog Feed Moderator Site Dashboard for each author to analyse his interactions Notifications for badges earned, moderation, chats, etc Messenger and a few more. I am confused with how many apps do i have to make. currently i have : Blog feed notifications blog admin (for moderator to check posts are according to the code of conduct) blog editor Should the settings be a different app. Should there be a different app for dashboard. I have a few there details like saving billing information which i will be using in other projects. There are other so many things in settings site. should different settings forms like email notification and billing , organization, notification settings, themes settings be different apps. I would like to know how i should structure the project and apps. -
django sweetalert2 activite when the data Inserted succesfully
I read this https://github.com/Atrox/sweetify-django documentation about sweetify2, and i did everything say in the documentation.but everytime the user admin Insert new data, the sweetify didnt activate, did i miss something? I have this code in my html <form method="POST" action-xhr="/InsertProduct/" enctype="multipart/form-data"> {% csrf_token %} .... <button type="submit" name="submit" id="submit">Submit</button> </form> this is my views.py import sweetify def InsertProduct(request): .... insert_data = Product( .... ) insert_data.save() sweetify.success(request, 'You did it', text='Good job! You successfully showed a SweetAlert message', persistent='Hell yeah') return redirect('/') sweetify.py from sweetify.templatetags import sweetify sweetify.DEFAULT_OPTS = { 'showConfirmButton': False, 'timer': 2500, 'allowOutsideClick': True, 'confirmButtonText': 'OK', } i already read this documentation https://github.com/Atrox/sweetify-django, i am using django -
'dict' object has no attribute 'capitalize'
Straight to the point: when creating a file with full_content.create i get the error 'dict' object has no attribute 'capitalize'. I use django.forms and inside my class InputForm use the method cleaner_data. My guess is, when i access the title itself after the cleaning, it's a None. Util.py: def create_file(title, content): if default_storage.exists(f"entries/{title}.md"): return False else: f = open(f"entries/{title.capitalize()}.md", mode='w+') f.write(content) f.close() return True forms.py: class InputForm(forms.Form): title = forms.CharField(label="Enter a title") content = forms.CharField(label="Enter content", widget=forms.Textarea()) def clean_title(self): title_name = self.cleaned_data.get("title") filename = f"entries/{title_name}.md" if not default_storage.exists(filename): return self.cleaned_data else: forms.ValidationError("This title is already taken") def create(self): title = self.cleaned_data["title"] content = self.cleaned_data["content"] util.create_file(title, content) views.py: def create(request): if request.method == "POST": full_content = forms.InputForm(request.POST) if full_content.is_valid(): full_content.create() #return render(request, "encyclopedia/entry.html",{ # "title": "util.get_page_name(title)", # "entry": "util.get_entry(title)" # }) return HttpResponse("Test page. What i want is below to output is above") return render(request, "encyclopedia/create.html", { "title":forms.InputForm()["title"], "content":forms.InputForm()["content"] }) -
Implement "through" in already existent ManyToMany
I'm dealing with this complex scenario, and I'm not quite sure how to proceed. Context: I have this situation: class Cat(models.Model): treats = models.ManyToManyFields(Treat) class Treat(models.Model): name = models.CharField() This relation is a legacy one, there's already data in production. Problem: A new restriction has come up, in which the Treat model has to be moved to a new database. That means, in short, I have to separate the constraint with treats from cat. Proposal: I've been told that, given my scenario, I have no choice but to implement a custom intermediate model to preserve the m2m but to also allow for the db_constraint=False. The suggestion was something like: class Cat(models.Model): treats = models.ManyToManyFields(Treat, through=CatTreat, related_name="cats") class Treat(models.Model): name = models.CharField() class CatTreat(models.Model): cat = models.ForeignKey(Cat) treat = models.ForeignKey(Treat, db_constraint=False) In my local stack, after running the migrations I've found myself that I can't access the data. from apps.animals.models import Cat cat = Cat.objects.first() cat.treats # => animals.Treat.None cat.treats.through.objects.all() # => <Queryset []> I'm not sure if the new through method is not configured correctly or if I have inadvertently delete my data. Any insight is appreciated. -
Display PostGis Geometry in Leaflet (Javascript) using Django
Following the Leaflet Quick Start Guide https://leafletjs.com/examples/quick-start/ I query a world_border, which has a geometry-field mpoly (outer shape of country) and a lat/lon-field (center position) that I want to display on my html-site. I have been able to show display the lat/lon point. But how do I (smartly) visualize the Multipoligon? Adding {{ world_border.mpoly }} to map.html prints: RID=4326;MULTIPOLYGON (((8.710255 47.696808, 8.678595 47.693344, ... ))) This is what the table looks like (pgAdmin) SELECT * FROM world_worldborder WHERE name Like '%Germany%'; shows https://i.stack.imgur.com/wPp6u.png views.py from django.contrib.gis.geos import Point from django.shortcuts import render from .models import WorldBorder def map(request): pnt = Point(9.003889, 48.661944) world_border = WorldBorder.objects.get(mpoly__intersects=pnt) return render(request, 'world/map.html', {'world_border':world_border}) map.html {% extends 'home/base.html'%} {% block content %} <!-- Leaflet --> <link rel="stylesheet" href="https://unpkg.com/leaflet@1.6.0/dist/leaflet.css" integrity="sha512-xwE/Az9zrjBIphAcBb3F6JVqxf46+CDLwfLMHloNu6KEQCAWi6HcDUbeOfBIptF7tcCzusKFjFw2yuvEpDL9wQ==" crossorigin=""/> <script src="https://unpkg.com/leaflet@1.6.0/dist/leaflet.js" integrity="sha512-gZwIG9x3wUXg2hdXF6+rVkLF/0Vi9U8D2Ntg4Ga5I5BZpVkVxlJWbSQtXPSiUTtC0TjtGOmxa1AJPuV0CPthew==" crossorigin=""></script> <div id="mapid" class="w-100 h-100"> <script> var zoom = 10; var lat = {{world_border.lat}} var lon = {{world_border.lon}} var mymap = L.map('mapid').setView([lat, lon], zoom); L.tileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a>', subdomains: ['a','b','c'] }).addTo(mymap); var marker = L.marker([lat, lon]).addTo(mymap); </script> </div> {% endblock %} -
How to overwrite the default formfield and give `formfield_for_manytomany` a field of the edited object?
How can I give formfield_for_manytomany the ForeignKey exchange of the edited object? What I'm trying to achieve is to override the default formfield for a many to many field with only the markets of a specific exchange defined with a ForeignKey on the edited object. Something like Market.objects.filter(exchange=edited_object.exchange). How can I do that? admin.py @admin.register(Strategy) class CustomerAdmin(admin.ModelAdmin): def formfield_for_manytomany(self, db_field, request, **kwargs): if db_field.name == "markets": kwargs["queryset"] = Market.objects.filter(exchange=?) # <--- Here return super().formfield_for_manytomany(db_field, request, **kwargs) models.py class Exchange(models.Model): pass class Market(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, null=True) class Strategy(models.Model): exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, null=True) markets = models.ManyToManyField(Market, blank=True) Thank you, -
Django file save
I am having a problem when i want to upload a form. I will attach a image with the problem and some code. Tell me what i did wrong.I want to save the files i will upload on the upload form, and i cannot because of this error it goes when i try to submit the form. Thank you in advance. Error image and the code is: from django import forms from django.utils.translation import ugettext_lazy as _ from Upload_Page.models import Form_Data class Upload_Document(forms.ModelForm): class Meta: model= Form_Data labels = { 'title':'Title', 'author':'Author(s)', 'document_type':'Document type', 'keywords':'Keywords', 'abstract' :'Abstract', 'authentication':'Access type', 'site':'Website', 'comments':'Additional comments', 'file_upload':'Browse' } fields =['title','author','document_type','keywords','abstract','authentication','site','comments','file_upload'] the model is: from django.db import models DOCUMENT_TYPES = [ ('Tehnical report','Tehnical report'), ('Bachelor thesis','Bachelor thesis'), ('Master thesis','Master thesis'), ('PhD thesis','PhD thesis'), ('Scientific article','Scientific article'), ('Other type','Other type'), ] DOCUMENT_AUTHENTICATION_LEVEL=[ ('Unrestricted','Unrestricted'), ('Restricted','Restricted'), ] # Create your models here. class Form_Data(models.Model): title=models.CharField(unique=True,max_length=100,blank=False) author=models.CharField(max_length=100) document_type=models.CharField(choices=DOCUMENT_TYPES,max_length=500,blank=False,default=None) keywords=models.CharField(max_length=500) abstract=models.TextField(null=True,blank=True) authentication=models.CharField(choices=DOCUMENT_AUTHENTICATION_LEVEL,blank=False,default=None,max_length=500) site=models.URLField(blank=True) comments=models.TextField(null=True,blank=True) file_upload=models.FileField(default=None) def __str__(self): return self.title class Authentication_Level(models.Model): title=models.ForeignKey('Form_Data',to_field='title', on_delete=models.CASCADE,related_name='title1') download_rights=models.CharField(max_length=500) def __str__(self): return self and the settings file is: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') STATIC_DIR = os.path.join(BASE_DIR, 'static') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: … -
ReportLab make a multipage table with header and footer
I'm trying to make a simple report that has a header/footer and table in the middle with a ot of rows. I'm new to ReportLab and the reason I switched from WeasyPrint is because I wanted the engine to handle page breaks nicely. Below is my code : def print_users(self): buffer = self.buffer doc = BaseDocTemplate(buffer, rightMargin=20, leftMargin=20, topMargin=20, bottomMargin=20, pagesize=landscape(self.pagesize)) frame = Frame( doc.leftMargin, doc.bottomMargin, doc.width, doc.height - inch * 0.5, id='normal', showBoundary=1) template = PageTemplate(id='all_pages', frames=frame, onPage=self._header_footer) doc.addPageTemplates([template]) styles=getSampleStyleSheet() # Our container for 'Flowable' objects elements = [] elements.append(Spacer(1, 3*units.cm)) title = self.event.name elements.append(Paragraph(self.event.name, styles["Normal"])) elements.append(Spacer(1, 1*units.cm)) data = [] titles = ['First name', 'Last name', 'Position', 'Institution'] data.append(titles) for invitation in self.invitations: line = [] line.append(invitation.person.firstname) line.append(invitation.person.lastname) line.append(invitation.person.position) line.append(invitation.institution.name) data.append(line) t=Table(data) t.setStyle(TableStyle( [('LINEBELOW',(0,0),(-1,-1),1, colors.gray)])) table_story = [t] elements.append(t) # t_keep = KeepInFrame(0, 0, table_story, hAlign='CENTER', vAlign='MIDDLE', fakeWidth=False) # write the document to disk # Draw things on the PDF. Here's where the PDF generation happens. # See the ReportLab documentation for the full list of functionality. # elements.append(t_keep) doc.build(elements) The header/footer are showing fine and so is the table , but when we go to the second page, the table overrides the header. I tried to add … -
Read a .pdf file uploaded through Django forms with Tabula or Fitz
I'm taking a pdf file from user and I want to read or perform some operations on the uploaded file, I'm unable to specify the location of the once uploaded and not able to read the file too. -
Django with apache-cassandra database with pycharm
I am trying to create message app with a database model using Django framework using pycharm with apache-cassandra as a database. When I try to run "python manage.py migrate" in the terminal I get the following error, TypeError: Unknown option(s) for sync_cassandra command: app_label, check_unapplied, fake, fake_initial, interactive, migration_name, plan, run_syncdb. Valid options are: database, force_color, help, no_color, pythonpath, settings, skip_checks, stderr, stdout, traceback, verbosity, version. My setting.py """ Django settings for DjangoProject project. Generated by 'django-admin startproject' using Django 3.1. For more information on this file, see https://docs.djangoproject.com/en/3.1/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.1/ref/settings/ """ import os from pathlib import Path from cassandra import ConsistencyLevel # Build paths inside the project like this: BASE_DIR / 'subdir'. from cassandra.cqlengine.connection import session BASE_DIR = Path(__file__).resolve(strict=True).parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 's6+mmj8j^9qe+jy&=@^2i!cao!fnxeicaa24c^@se8n@o88t&r' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'posts.apps.PostsConfig', ] INSTALLED_APPS = ['django_cassandra_engine'] + INSTALLED_APPS MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', … -
Django project on PythonAnywhere works but no functionality, although it does locally
I've just deployed my first site on PythonAnywhere, which is a Craigslist clone for which the search functionality works as expected locally but when deployed I can only access the homepage and then I get two different errors depending on the browser I try it on. Feel free to try it yourselves at http://matipule.eu.pythonanywhere.com/ This is Safari https://dpaste.com/3ZAJFC4PM This is Chrome https://imgur.com/PjvLrao Chrome claims having an issue with the CSRF but I've included the token in the form as you can see below and then again, it actually works locally so I'm clueless. This is the code where the token is in. <form action="{% url 'new_search' %}" method="post"> {% csrf_token %} <input type="text" name="search" placeholder="search"> <button class="btn waves-effect waves-light" type="submit" name="action">Submit <i class="material-icons right">send</i> </button> </form> -
Is it possible to receive Amazon SES emails via webhook?
I have a django app where I want to receive my inbound emails from Amazon's Simple Email Service on my own http endpoint, process them and then forward them elsewhere. Is that possible with a webhook, or should I look for another way? -
How to use js in django template?
I have problem with javascript in django. My 'Hello Wold' app called alert doesnt work in django templete. How to fix it? profile.html {% load static %} <link rel="stylesheet" href="{% static 'scripts/profile/alert.js' %}"> <script src="scripts/profile/alert.js"></script> cmd: Not Found: /home/profile/scripts/profile/alert.js my folders https://i.stack.imgur.com/1QYAk.png -
django one to many - query all related objects and use it in template
I need some help with one to many relation. For given models: class Device(models.Model): name=models.CharField(max_length=10,blank=True) software=models.ManyToManyField(Software,default=None,blank=True) class Software(models.Model): name=models.CharField(max_length=10,blank=True) class Address_IP(models.Model): adres_IP=models.CharField(max_length=12,default='127.0.0.1',blank=True) device=models.ForeignKey(Device,default=None,blank=True,null=True,on_delete=models.CASCADE) To query all objects including 'Software' i'm using query as below: q=Device.objects.all().prefetch_related('Software') How can i also get all related 'Address_IP' considering that device can have many IP addresses ( iLo, mgmt,eth) and list them in template ? Query as shown below shows errors: q=Device.objects.all().prefetch_related('Software').address_IP_set.all() "'QuerySet' object has no attribute 'address_IP_set'" Regards -
What does 'request.GET.get' in an API creation do in Django and how does it work precisely?
I'm watching a lecture about Django. The lecturer explains everything wonderfully but didn't go into much detail into "an API I effectively created". This is my first time meddling with this so I'm a bit unsure. What I don't understand is specifically this line request.GET.get("start"). How does one make that work in the index.html file (with embedded js script) by just using a fetch? views.py def posts(request): # Get start and end points start = int(request.GET.get("start") or 0) end = int(request.GET.get("end") or (start + 9)) # Generate list of posts data = [] for i in range(start, end + 1): data.append(f"Post #{i}") # Artificially delay speed of response time.sleep(1) # Return list of posts return JsonResponse({ "posts": data }) index.html fetch(`/posts?start=${start}&end=${end}`) .then(response => response.json()) .then(data => { data.posts.forEach(add_post); }) -
Django celery beat scheduler not working at Asia/Calcutta timezone
I am using Django celery beat with celery, Problem which I am facing is my when I am using scheduler provided by Django-celery beat it doesn't work but using normal beat without scheduler provided by Django-celery-beat works with below command Doesn't works => celery worker --app=my_project.celery_app -l info --beat --scheduler django_celery_beat.schedulers:DatabaseScheduler Works => celery worker --app=my_project.celery_app -l info --beat one thing I noticed when I change Time_Zone to 'UTC' Django-celery-beat scheduler starts working, but i don't want to change timezone settings for djagno how do I fix this please find my settings below USE_TZ = False TIME_ZONE = 'Asia/Kolkata' CELERY_TIMEZONE = 'Asia/Kolkata' -
How to access OrderItems for a specfic order via foreignkey
I am building an online shop to sell music. I have a problem with my ProfileView, where I want to show the customer his finished orders with the files that he has purchased. Here are my models: class Product(models.Model): title = models.CharField(max_length=50) slug = models.SlugField() description = models.TextField() image = models.ImageField(upload_to='product_images') file = models.FileField(upload_to='product_files') created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) active = models.BooleanField(default=False) soundkit = models.BooleanField(default=False) licence_variation = models.ManyToManyField(LicenceVariation) def get_absolute_url(self): return reverse("cart:product-detail", kwargs={'slug': self.slug}) def get_delete_url(self): return reverse('staff:product-delete', kwargs={'pk': self.pk}) def is_soundkit(self): return self.soundkit def __str__(self): return self.title def get_update_url(self): return reverse("staff:product-update", kwargs={'pk': self.pk}) class OrderItem(models.Model): order = models.ForeignKey("Order", related_name='items', on_delete=models.CASCADE) product = models.ForeignKey(Product, on_delete=models.CASCADE) licence_variation = models.ForeignKey(LicenceVariation, on_delete=models.CASCADE) def __str__(self): return self.product.title def get_raw_total_item_price(self): return self.licence_variation.price def get_total_item_price(self): price = self.get_raw_total_item_price() return "{:.2f}".format(price / 100) class Order(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE) start_date = models.DateTimeField(auto_now_add=True) ordered_date = models.DateTimeField(blank=True, null=True) ordered = models.BooleanField(default=False) billing_address = models.ForeignKey(Address, related_name='billing_address', blank=True, null=True, on_delete=models.SET_NULL) shipping_address = models.ForeignKey(Address, related_name='shipping_address', blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return self.reference_number @property def reference_number(self): return f"Order-{self.pk}" def get_raw_subtotal(self): total = 0 for order_item in self.items.all(): total += order_item.get_raw_total_item_price() return total def get_subtotal(self): subtotal = self.get_raw_subtotal() return "{:.2f}".format(subtotal / 100) def get_raw_total(self): subtotal = self.get_raw_subtotal() return subtotal def get_total(self): … -
unable to show data entered in textarea
my views.py code: `from django.shortcuts import render from .forms import * from .models import for_point,against_point def index(request): return render(request,'debate_sample/content.html') def for_view(request): if request.method == 'POST': form = for_form(request.POST) if form.is_valid(): form.save() all_items = for_point.objects.all return render(request,'debate_sample/home.html',{all_items:'all_items'}) else: all_items = for_point.objects.all return render(request,'debate_sample/home.html',{all_items:'all_items'}) def against_view(request): if request.method == 'POST': form = against_form(request.POST or None) if form.is_valid(): form.save() all_values = against_point.objects.all return render(request,'debate_sample/home2.html',{all_values:'all_values'}) else: all_values = against_point.objects.all return render(request,'debate_sample/home2.html',{all_values:'all_values'}) ` code in home.html and similar code in home2.html {% extends "debate_sample/content.html" %} {% block content %} <div class="#"> <p>for</p> {% if all_items %} {% for things in all_items %}<br/> {{things.for_text}} {% endfor %} {% endif %} <form class="form-inline my-2 my-lg-0" method="post"> {% csrf_token %} <textarea name="for_text" rows="8" cols="80"></textarea> <button type="submit" name="button">submit</button> </form> </div> {% endblock %} I am able to show the textarea and click on submit button but after clicking on submit button the text typed in textarea is not been shown below the textarea. I have created model and model forms to write my code in views. -
django + angular , displaying django error message in angular
I am creating an app for practice using Django(drf) and angular 8, i want to show error message sent by Django in case of any fail in validation. Problem is, i am not able to get the response body which contains error message in angular with {observe: event} while doing HTTP post with {observe: 'events'}, using {observe: 'events'} for progress bar. angular code postData( fileToUpload: File, empName: string, dept: string ): Observable<any> { const formData: FormData = new FormData(); formData.append("file", fileToUpload, fileToUpload.name); formData.append("emp_name", empName); formData.append("dept", dept); return this.http .post( "http://localhost:8000/post/add", formData, { reportProgress: true, observe: "events" } ) .pipe(tap((result) => {}, catchError(this.handleError<any>("postData")))); } above is call in below code public onSubmit(FileUploadFormData: NgForm) { let post: any = []; post = this.post; this.isFileUploading = true; const fileList: FileList = FileUploadFormData.value; this.empName = FileUploadFormData.value.empName; this.dept = FileUploadFormData.value.dept; this.uploadService.postData(this.file, this.empName, this.dept).subscribe( (response) => { switch (response.type) { case HttpEventType.Sent: console.log("inside sent"); break; case HttpEventType.ResponseHeader: console.log("inside header"); break; case HttpEventType.UploadProgress: this.percentage = Math.round( (response.loaded / response.total) * 100 ); console.log(`Uploaded! ${this.percentage}%`); break; case HttpEventType.Response: console.log("inside response", response.body); this.zone.run(() => { this.post = []; this.post = post; this.post.unshift(response.body); }); this.percentage = 0; } if (this.percentage == 100) { this.percentage = 0; this.isFileUploading = false; console.log(response.body); …