Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to display data base table by using forms.py in Django
My name is R Kartheek. I'm new to Django. I know how to display database table by using HTML in Django. But, I don't know by using forms.py. Present learning that. Anyone, please help me with how to print the database table by using forms.py in Django. Just like <.objects.all()> how to use this by using Forms.py in Django? models.py: from django.db import models # Create your models here. class Emp_Data(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) mobile = models.BigIntegerField() email = models.EmailField(max_length=50) company = models.CharField(max_length=50) location = models.CharField(max_length=50) salary = models.IntegerField() views.py from django.shortcuts import render from .models import Emp_Data from .forms import Emp_Data_Form from django.http import HttpResponse from django.contrib import messages # Create your views here. def Emp_View(request): if request.method == 'POST': form = Emp_Data_Form(request.POST) if form.is_valid(): first_name = request.POST.get('first_name') last_name = request.POST.get('last_name') mobile = request.POST.get('mobile') email = request.POST.get('email') company = request.POST.get('company') location = request.POST.get('location') salary = request.POST.get('salary') data = Emp_Data(first_name = first_name, last_name = last_name, mobile = mobile, email = email, company = company, salary = salary ) data.save() messages.success(request, f'Data submitted successfully...') form = Emp_Data_Form() context = {'form':form} return render(request, 'empformapp/empdata.html', context) else: return HttpResponse('Invalid form') else: form = Emp_Data_Form() context = {'form':form} return render(request, 'empformapp/empdata.html', … -
django paginator is not working but the link is working manually
I have a page that represents the articles based on categories. I am trying to make a pageinator for this page but I see no pageinator in my webpage. However when I enter the link manually it works. i don't know what I'm missing here... #my HTML page <div class="blog-pagination"> <ul class="justify-content-center"> {% if cat_articles.has_previous %} <li><a href="{% url 'website:category' cat_articles.previous_page_number %}"> <i class="icofont-rounded-left" ></i></a></li> {% endif %} <li><a href="#">1</a></li> <li class="#"><a href="#">2</a></li> <li><a href="#">3</a></li> {% if cat_articles.has_next %} <li><a href="{% url 'website:category' cat_articles.next_page_number %}"> <i class="icofont-rounded-right" ></i></a></li> {% endif %} </ul> </div> </div><!-- End blog entries list --> #my view def category(request, slug, page=1): cat = get_object_or_404(Category, slug=slug, status=True) articles_cat = cat.articles.filter(status='Published') paginator_cat = Paginator(articles_cat, 1) cat_articles = paginator_cat.get_page(page) context = { "category": cat_articles } return render(request, 'website/category.html', context) -
Server ERROR: smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server
This maybe a repeated question but I'm still facing issues on this, hope there's a solution around. Thanks in advance. I'm trying to send mail through my Gmail Account. I did get an App Password for it and everything. I'm using the newest version of Python. This is the Error I get: Traceback (most recent call last): File "E:\Python_old\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "E:\Python_old\venv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "E:\Python_old\venv\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "E:\Python_old\WebshopV4\ecommerce\store\views.py", line 71, in checkout send_mail( File "E:\Python_old\venv\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "E:\Python_old\venv\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "E:\Python_old\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 102, in send_messages new_conn_created = self.open() File "E:\Python_old\venv\lib\site-packages\django\core\mail\backends\smtp.py", line 67, in open self.connection.starttls(keyfile=self.ssl_keyfile, certfile=self.ssl_certfile) File "C:\Users\Jeamp\AppData\Local\Programs\Python\Python38\lib\smtplib.py", line 755, in starttls raise SMTPNotSupportedError( smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Here is my Email configuration: # Email Settings EMAIL_HOST = 'smtp.gmail.com' Email_PORT = '587' EMAIL_HOST_USER = 'jeampo.jeampo@gmail.com' EMAIL_HOST_PASSWORD = 'MYPASSWORD' EMAIL_USE_TLS = True And here is my Django sendmail() function: # send an email send_mail( 'message from ' + message_name, # subject message_to_send, # message message_email, # from email ['myemail@outlook.de'], # To Email ) -
how to update value in database in django?
code It is Screenshot of my code for delete and update in django database. but here if I click on delete button it correctly deletes the targited value but if i press update button of any record it only update and show the value of last record. here I'm attaching the output screenshots main_output here if i print on any of update button it will show and update only the most recently added record modal -
Why does my heroku bash instance show my app folder to be empty?
I've deployed an app to heroku and ran heroku run bash -a {app_name} Once it successfully opens a bash console and I run ls I see nothing. If I run pwd it says I'm in the /app directory where my project files should be. I am also unable to run any commands using my manage.py file e.g. heroku run python manage.py migrate results in a python: can't open file 'manage.py': [Errno 2] No such file or directory -
'DatabaseOperations' object has no attribute 'geo_db_type'
I'm using 2 databases in my project. Sqlite3 for most things and then Postgis to create a geospatial database for my 'store locator' app. What I've done so far: 1] My postgres DB has been setup with the postgis extension 2] I have added the database in my settings.py, and also added'django.contrib.gis' under INSTALLED_APPS. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }, 'geospatial': { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME': 'geospatial', 'USER': '*****', 'PASSWORD': '*****', 'HOST': 'localhost', 'PORT': '5432' } } 3] I came across 'Database Routers' to make sure that my app was using the postgis db and not the default sqlite3 one and gave it a go but to no avail. facility/routers.py: from django.conf import settings class dbRouter(object): def db_for_read(self, model, **hints): if model._meta.app_label == 'facility': return 'geospatial' return None def db_for_write(self, model, **hints): if model._meta.app_label == 'facility': return 'geospatial' return None def allow_relation(self, obj1, obj2, **hints): if obj1._meta.app_label == 'facility' or obj2._meta.app_label == 'facility': return True return None def allow_syncdb(self, db, model): if db == 'geospatial': return model._meta.app_label == 'facility' elif model._meta.app_label == 'facility': return False return None mainapp/settings.py: DATABASE_ROUTERS = ['facility.routers.dbRouter'] Can someone please tell me what I'm doing wrong? Any and all help is … -
Staticfiles not copied to STATIC root (0 static files copied)
I am trying to get my app on heroku have the relevant settings as follows STATICFILES_DIRS = (os.path.join(BASE_DIR, "static"),) if not DEBUG: AWS_ACCESS_KEY_ID = get_environment_variable("AWS_ACCESS_KEY_ID") AWS_SECRET_ACCESS_KEY = get_environment_variable("AWS_SECRET_ACCESS_KEY") AWS_STORAGE_BUCKET_NAME = "the-bucke-name" AWS_CUSTOM_DOMAIN = f"{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com" AWS_DEFAULT_ACL = "public-read" AWS_LOCATION = "static" STATIC_URL = f"https://{AWS_CUSTOM_DOMAIN}/{AWS_LOCATION}/" AWS_S3_OBJECT_PARAMETERS = { "CacheControl": "max-age=86400", } STATICFILES_STORAGE = "storages.backends.s3boto3.S3Boto3Storage" else: STATIC_URL = "/staticfiles/" STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles") import django_heroku django_heroku.settings(locals(), staticfiles=False) When i run docker-compose run --rm web-app python manage.py collectstatic --noinput I get 0 static files copied to '/code/staticfiles' locally and on heroku 0 static files copied I cant seem to figure out which setting I am missing. The staticfiles folder is empty so not a case of unmodified files or there being no chnages to the css. -
Use video part as thumbnail
In you when upload videos with thumbnail on feed show that. But when no upload video with thumbnail YouTube randomly choose thumbnail from video part how to do this use python and django. -
How to prevent deletion of instance from Inline in Django Admin correctly?
I have two models look like: class Client(models.Model): # some client fields class User(models.Model): # some user fields owned_by = models.ForeignKey(Client, on_delete=models.CASCADE) is_main_user = models.BooleanField() Also I made admin part. StackedInline for User and ModelAdmin for Client which includes UserStackedInline. My goal is prevent deleting User which has is_main_user==True. I've made signal handler for pre_delete from User and raise ValidationError("You cannot delete main user") when condition is true. But when I try to delete user in admin, I was getting 500 error. I've expected to get readable message in admin. How I can correctly handle ValidationError on instance deletion in StackedInline? Or am I incorrectly preventing a specific instance from being deleted? -
NoReverseMatch at / Reverse for 'blog' not found. 'blog' is not a valid view function or pattern name
Not sure why I'm getting this error. It also says: "Error during template rendering In template /Users/aydanaslanova/Desktop/Travel_Project/todo/templates/todo/base.html, error at line 0" I don't have a blog.html or a blog url or a blog view? I only have one app (todo), that'all. For reference, I tried to add another app earlier called "blog" but later deleted it. Attaching settings.py, urls.py and base.html where I am getting the error. Similar questions were not helpful, unfortunately. -
Django model.FilePathField returns paths that have additional 'static' directories
I am new to Django, writing my first project (portfolio website) and stumbled upon such problem: So i a nutshell: model.FilePathModel when called in my .html site as {% static project.image %} returns: /static/projects/static/img/project1.png while it should return: /static/projects/img/project1.pn My question is: Why does addtional /static/ appears when there is none in my file sturcture? I am not sure if something with my understanding of Django static file managment is wrong, or of models.FilePathField for that matter. dir sturcture: Link to the snapshot procejts/models.py file : class Project(models.Model): allow_folders=True def __str__(self): return self.title title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length = 20) image = models.FilePathField(path='projects/static/projects/img' ) settings.py(static settings part) STATIC_URL = '/static/' STATICFILES_DIRS = [ BASE_DIR / "static", BASE_DIR /'projects/static/', ] -
line 254, in add_coupon order.coupon = get_coupon(request, code) AttributeError: 'dict' object has no attribute 'coupon'
I am creating a django3 Ecommerce website and I've come through the following error when a guest user tries to enter a coupon : Traceback (most recent call last): File "/Users/miryamelliye/development/comdjanco/osivenv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Users/miryamelliye/development/comdjanco/osivenv/lib/python3.7/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/miryamelliye/development/comdjanco/ecommerce/store/views.py", line 254, in add_coupon order.coupon = get_coupon(request, code) AttributeError: 'dict' object has no attribute 'coupon' views.py def get_coupon(request, code): try: coupon = Coupon.objects.get(code = code) return coupon except ObjectDoesNotExist: messages.info(request, 'This coupon does not exist') return redirect('checkout') def add_coupon(request): data = cartData(request) if request.method == "POST": form = CouponForm(request.POST or None) if form.is_valid(): try: code = form.cleaned_data.get('code') order = data['order'] order.coupon = get_coupon(request, code) order.save() messages.success(request, 'Successfully added coupon!') return redirect('checkout') except ObjectDoesNotExist: messages.info(request, 'You do not have an active order') return redirect('checkout') return redirect('checkout') my utils.py def cookieCart(request): #Create empty cart for now for non-logged in user try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('CART:', cart) items = [] order = {'get_cart_total':0, 'get_cart_items':0, 'shipping':False} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]['quantity'] product = Product.objects.get(id=i) total = (product.price * cart[i]['quantity']) order['get_cart_total'] += total order['get_cart_items'] += cart[i]['quantity'] item = { 'id':product.id, 'product':{'id':product.id,'name':product.name, 'price':product.price, 'imageURL':product.imageURL}, 'quantity':cart[i]['quantity'], … -
django 1.8.5 + Python 2.7 to Django 3.0 + Python 3.9
I have a massive Django 1.8.5 and Python 2.7.6 project. I need to upgrade it to Django 3.0, Python 3.9. Any recommendations on how to proceed ? Thanks. -
Cancel a save from save method in django models
So I have django model and I want to override save so that it only saves on certain instances. Is there a way to avoid a save from happening if a condition is met? The idea is if certain conditions defined with an if statement aren't met the instance fails to be saved. so for instance if there is not enough waiters we cancel the save, or if there is not enough tables we do the same. Here's my code: class Service(models.Model): id = models.AutoField(primary_key=True) arrival = models.DateTimeField(auto_now_add=True) exit = models.DateTimeField(null=True, blank=True) waiter = models.ForeignKey('Waiter', on_delete=models.CASCADE) table = models.ForeignKey('Table', on_delete=models.CASCADE) total_ammount= models.DecimalField(max_digits=15, decimal_places=2) def save(self, *args, **kwargs): if self.id == None: time = datetime.datetime.now() # check for waiters waiters = Waiter.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all() available_waiters = waiters.filter(num_Service__lt=4) avalable_waiters_length = len(available_waiters) # check for tables tables = Table.objects.select_related().annotate(num_Service=Count('service', filter=Q(service__exit__gt=time))).all() available_tables = tables.filter(num_Service__lt=1) avalable_tables_length = len(available_tables) # return exception if a problem arises if avalable_tables_length == 0 and avalable_waiters_length == 0: print("not enough waiters or tables") if avalable_waiters_length == 0: print("not enough waiters") return if avalable_tables_length == 0: print("not enough tables") return # assign waiter and table waiter_obj = random.choice(available_waiters) self.waiter = waiter_obj table_obj = random.choice(available_tables) self.table = table_obj print(time.time()) # check if current … -
How do i go about making a django model field unique but only for individual users?
So I have this watchlist model class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='watchlist') symbol = CharField(max_length=10, unique=True) Where a user and a text symbol is saved. A user is not allowed to save two of the same symbol cuz that wouldnt be good logic. Thats why i added the unique=True. However, I later realized that i kinda misunderstood what unique does and that its unique across the whole table no matter who the user is. I only want it to be unique when the user is the same. So Test_User can save "ABC" and "DEF" but cant save "ABC" again. However User123 should be allowed to save "ABC" and so on. One bad solution to this would be taking care of it in my views when i save instances by getting a list of symbols saved already and checking if the given symbol is in that list or not and save accordingly. I consider this a bad solution because it wont work in admin and the redundancy will be insane if i need to use it in other views -
(djstripe.C001) Could not find a Stripe API key. HINT: Add STRIPE_TEST_SECRET_KEY and STRIPE_LIVE_SECRET_KEY to your settings
Stripe keys are not being detected correctly and I don't know where the error is in DJStripe. Here is how my Stripe is configured: STRIPE_SECRET_KEY = os.environ.get("STRIPE_SECRET_KEY", "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_PUBLIC_KEY = os.environ.get("STRIPE_PUBLIC_KEY", "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx") STRIPE_TEST_SECRET_KEY = "sk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx STRIPE_TEST_PUBLIC_KEY = "pk_live_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" -
How to export models from admin page with username rather than user id?
I have a participant model in models.py Django as the following: from django.db import models from django.contrib.auth.models import User class Participant(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) score = models.FloatField(default=0) completed_study = models.BooleanField(default=False) def __str__(self): return self.user.username and I want to be able to export all the data from the admin page, so under the admin.py I added the following from django.contrib import admin from .models import Participant from django.contrib.auth.admin import UserAdmin as BaseAdmin from import_export.admin import ImportExportModelAdmin from import_export import resources from django.contrib.auth.models import User class UserResource(resources.ModelResource): class Meta: model = User fields = ('id', 'username') class UserAdmin(BaseAdmin, ImportExportModelAdmin): resource_class = UserResource class ParticipantAdmin(admin.ModelAdmin): list_display = ['user', ] readonly_fields = ('created_at', 'updated_at',) class ParticipantAdmin(ImportExportModelAdmin): pass admin.site.register(Participant, ParticipantAdmin) admin.site.unregister(User) admin.site.register(User, UserAdmin) I am able to export the data from the participant model, but I want under the user field to display the actual username rather than the id. How can I do that? is that even doable? -
request.user in generic view and in pure function in django
I was using django-rest-framework-simplejwt for authentication. Here is my settings.py filesettings.py file Initially I was trying to get login user by accessing request.user in a view function as shown below and passing access token in headers berear token: function test But I wasn't able to get the logged in user. Instead when I tried RetreiveAPIView of rest framework generics, it gave me the user..Here is the code for the same..Using RetreiveAPIView UserSerializer Initially I thought that both the request objects are same but it seems that there is some difference.. Can anyone explain me what is the difference between the two? -
Django Error Following Tutorial b/c using 3.1 not 1.9 TypeError: view must be a callable or a list/tuple in the case of include()
I know what the issue is, its that in my code I cant use a string to map my views to urls but Im not sure how to rewrite it so that it works. urls. py from django.contrib import admin from django.urls import path urlpatterns = [ path('admin/', admin.site.urls), path('posts/', "posts.views.post_home"), ## *how do i rewrite this section* ] apps.py from django.apps import AppConfig class PostsConfig(AppConfig): name = 'posts' views.py from django.http import HttpResponse from django.shortcuts import render # Create your views here. def post_home(request): return HttpResponse("<h1>Hello</h1>") -
How do I load image from Django REST API?
So as stated, I'm having trouble loading images from Django backend(fetch works fine). I've looked other similar questions, but NONE OF THEM HELPED, sadly. So here's my Django code: settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') urls.py from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) model.py class Content(models.Model): objects = models.Manager() image = models.ImageField(upload_to='None', height_field=None, width_field=None, max_length=None, null=True, blank=True) key_line = models.CharField(max_length = 100, null=True) ### All 페이지에 보여지는 핵심 문장 body = models.TextField(blank=True, null=True) ### 발췌 내용 I've uploaded an image named 'eeee.PNG', and I can see the data serialized in JSON format like below: [ { "id": 5, "image": "/media/None/eeee.PNG", "key_line": "key.", "body": "blablabla", }, ] And my React code (fetch has been successfully worked) : <Container classname=""> <Row className=""> <Col className="text-text img-eachcake">{this.props.image}</Col> <Col className="text-text img-eachcake" src={this.porps.image}></Col> </Row> </Container> As you can see, I've tried two ways but none of them worked. What do you think is the problem? All the other props are loaded fine. It's just the image file that doesn't work. +in the inspection mode > Elements, I see the line as : <div src="/media/None/eeee.PNG" class="text-text img-eachcake col"></div> -
Pagination feature not working and paginator bar styling is off
I have two bugs in my code, First bug is a styling bug or frontend bug, Second bug is Pagination not working. The second bug is I'm trying to make the button active depending on what page it is, The button only lights up for page 1, When I go to page 2 the button is still active or lit up. The first bug for styling is the buttons were meant to look like this: but they look like this: Current code: <div class="row"> <div class="col-md-12"> {% if listings.has_other_pages %} <ul class="pagination"> {% if listings.has_previous %} <li class="page-item"> <a href="?page={{listings.previous_page_number}}" class="page-link">&laquo;</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link">&laquo;</a> </li> {% endif %} </ul> {% endif %} {% for i in listings.paginator.page_range %} {% if listings.number == i %} <li class="page-item active"> <a class="page-link page-item">{{ i }}</a> </li> {% else %} <li class="page-item"> <a href="?page{{i}}" class="page-link">{{i}}</a> </li> {% endif %} {% endfor %} </div> </div> Intended to look code <div class="row"> <div class="col-md-12"> <ul class="pagination"> <li class="page-item disabled"> <a class="page-link" href="#">&laquo;</a> </li> <li class="page-item active"> <a class="page-link" href="#">1</a> </li> <li class="page-item"> <a class="page-link" href="#">2</a> </li> <li class="page-item"> <a class="page-link" href="#">3</a> </li> <li class="page-item"> <a class="page-link" href="#">&raquo;</a> </li> </ul> </div> … -
How to temporary store a generated image for download
I have written some code for taking an image, and adding some text to it. Currently it just saves the file locally, but I would like it to store the new generated image temporary, so when the session is closed the file is deleted. Also, so in the future multiple users would be able to use the function at the same time, without one user owerwriting another ones image. My current code is: def Output(request): inputValue = request.GET.get('t', '') my_image = Image.open(os.path.join(BASE_DIR, 'media', 'blank.jpg')) title_font = ImageFont.truetype(os.path.join(BASE_DIR, 'homepage', 'static', 'homepage', 'Mistral.ttf'), 60) title_text = inputValue image_editable = ImageDraw.Draw(my_image) image_editable.text((45,333), title_text, (0, 0, 0), font=title_font) my_image.save(os.path.join(BASE_DIR, 'media', 'result.jpg')) return TemplateResponse(request, 'homepage/output.html', {'title': 'Output'}) so instead os saving the image locally as result.jpg, how do I save it temporary for a specific session? -
django channels redis took too long to shut down and was killed
so i was trying to do some basic stuff with channels. i wrote a script in my html to return a message script <script> const chatsocket = new WebSocket( 'ws://'+window.location.host+'/ws/test/' ) chatsocket.onmessage = function (e) { const data = JSON.parse(e.data) console.log(data) chatsocket.close() } </script> my consumers.py from channels.exceptions import StopConsumer from channels.generic.websocket import AsyncWebsocketConsumer import json class NotificationConsumer(AsyncWebsocketConsumer): async def connect(self): self.group_name = 'notificationgroup' await self.channel_layer.group_add( self.group_name, self.channel_name ) await self.accept() await self.channel_layer.group_send( self.group_name, { 'type': 'tester_message', 'tester': 'hello world' } ) async def tester_message(self, event): tester = event['tester'] await self.send(text_data=json.dumps({ 'tester': tester })) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.group_name, self.channel_name ) raise StopConsumer() so basically i get my desired output in the console... when i have CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer' } } but when i use an aws redis cluster (after installing channels-redis obviously) CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { "hosts": [('aws redis endpoint', 6379)], }, }, } i get this error WebSocket HANDSHAKING /ws/test/ [127.0.0.1:51551] WebSocket DISCONNECT /ws/test/ [127.0.0.1:51551] Application instance <Task pending name='Task-4' coro=<StaticFilesWrapper.__call__() running at E:\intes\sync\shero\venv\lib\site-packages\channels\staticfiles.py:44> wait_for=<Future pending cb=[BaseSelectorEventLoop._sock_write_done(1216)(), <TaskWakeupMethWrapper object at 0x000001F7D5226C70>()]>> for connection <WebSocketProtocol client=['127.0.0.1', 51551] path=b'/ws/test/'> took too long to shut down and was killed. what … -
Error message on entering duplicate in django form
I am trying to avoid duplicate email in my website form . Till now I was able to do this: 1.Whenever I enter duplicate email, it navigate back to homepage and user is not saved{ In my case team is not joined}. 2.In admin page when I try to enter duplicate email , I get my error message of duplicate email address I want this message in my form too, but it navigates to homepage. This is my model in models.py: class Team(models.Model): username = models.CharField(max_length=100) email = models.EmailField(max_length=100,unique=True,error_messages={'unique':"Email already exists"}) contact=models.IntegerField(null=False,blank=False,default=1234567890) def __str__(self): return self.username This is my form in forms.py: class TeamMembers(forms.ModelForm): username = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100,error_messages={'unique':"Email already exists"}) contact=forms.IntegerField(required=True) class Meta: model=Team fields = ['username','email','contact'] This is my function in views.py class TeamMembers(forms.ModelForm): username = forms.CharField(required=True,max_length=100) email = forms.EmailField(required=True,max_length=100,error_messages={'unique':"Email already exists"}) contact=forms.IntegerField(required=True) class Meta: model=Team fields = ['username','email','contact'] This is my join_team.html {% extends 'base.html' %} {%load crispy_forms_tags%} {% block content %} <div class="content-section"> <form method="POST"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Join our team</legend> {{form|crispy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Join</button> </div> </form> </div> {% endblock content %} I want to display error message on form page instead of going to homepage. I … -
I need to show date in formatted (like a short date ) in django page
I need to show date in formatted (like a short date ) in django page . I changed in settings.py USE_L10N = False and DATE_FORMAT = '%y-%m-%d' DATE_FORMAT = 'Y-m-d' And in templates : <h2> Created at : {{ data.date|date:'Y-m-d'}}</h2> But , I get blank output (no date displayed) , I get it when I print onlt data.date but in the following format : 2021-02-10T16:48:04.401985Z I need a cleaner format . my models.py : date = models.DateTimeField(default=now, editable=False)