Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to save image in current user used only model using Django?
model.py class Imageadd(models.Model): image_owner = models.ForeignKey(Profile,null=True,blank=True,on_delete=models.CASCADE) image = models.ImageField(default='default.jpg',upload_to='blood/') date = models.DateTimeField(default=now) def __str__(self): return str(self.image_owner) views.py def bloodImage(request): if request.method == 'POST' and request.FILES['pic']: image = request.FILES['pic'] img_obj = Imageadd(image=image) index.html <form action='' method='post' enctype="multipart/form-data"> {% csrf_token %} <input type='file' name='pic' accept='image/*' class="custom-file-input"> <input type='submit' class="button"> </form> -
How to redirect an admin user to redirect to the index page after logout from the default admin site in django?
I am using Django's default admin dashboard for the landing page for an admin. I want to redirect the admin from the default Django admin site to the index page-(which is the homepage for all -users). How Can I do that? -
Django does not redirect to NEXT when login is required
I am using a custom signin view, the problem is when I go to a page which have the @login_required decorator, it redirect the user to the signin page, but after the user is logged it does not redirect him to the initial page but When I use the login view provided by Django, it redirects to the desired page after login. urls.py urlpatterns = [ path("signin/", views.signin, name="signin"), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'), ] views.py def signin(request): if request.method == "POST": form = UserLoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] #login user = authenticate(username=username, password=password) if user is not None: if user.is_active: auth_login(request, user) else: pass else: messages.add_message(request, messages.INFO, mark_safe( "Sorry, your password was incorrect. Please double-check your password.")) else: form = UserLoginForm() return render(request, "users/signin.html", {'form' : form}) -
I have a record template, it is creating well and when I open the edit template what I do is create a new record
I have the saveremission method, where the form that is in HTML creates it perfectly and loads it to the DB. def guardarremision(request): if request.method == 'POST': fecharemi = request.POST['fecharemi'] fechaenvio = request.POST['fechaenvio'] clienteremi = request.POST['clienteremi'] enviadoa = request.POST['enviadoa'] fecharecibido = request.POST['fecharecibido'] telefonoremi = request.POST['telefonoremi'] formaenvio = request.POST['formaenvio'] statusremi = request.POST['statusremi'] preparadaremi = request.POST['preparadaremi'] guiaremi = request.POST['guiaremi'] remisiones = Remisiones( fecha = fecharemi, fecha_envio = fechaenvio, clientes_id = clienteremi, contacto = enviadoa, fecha_recibido = fecharecibido, telefono = telefonoremi, id_transporte_id = formaenvio, id_status = statusremi, elaborado = preparadaremi, guia = guiaremi ) remisiones.save() return HttpResponse("Remision Creada") else: return HttpResponse("Remision no puede ser creada") When I go to edit I have the following method, I have another template with a form that brings all the information through the ID, but when I save the edition it creates a new record. def editar_remision(request, id): remision = Remisiones.objects.get(pk=id) return render(request, "editar_remision.html", { 'remision' : remision }) I try to upload the edit template but I get an error. -
Django BaseManager.all() got an unexpected keyword argument 'Login'
I have database: class Users(models.Model): Login = models.OneToOneField(User, on_delete=models.CASCADE) <--- one to one field email = models.EmailField(max_length=255, unique=True, verbose_name='mail') balance = models.IntegerField(blank=False, verbose_name='balance') bonus = models.IntegerField(blank=True, verbose_name='count_bonus') def __str__(self): return str(self.Login.username) class Meta: verbose_name = 'Users' verbose_name_plural = 'Users' ordering = ['id'] and i need to query the database to get all the values by request.user, but i get the error. BaseManager.all() got an unexpected keyword argument 'Login' def Account(request): user = Users.objects.all(Login=request.user) context = { 'title' : 'title', 'user' : user, } return render(request=request, template_name='site/account.html', context=context) -
Getting the whole object of a related field in django
I have a model like this: class Cart(models.Model): id = models.UUIDField(primary_key=True, default=uuid4) customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True) class Reception(models.Model): PAYMENT_STATUS_PENDING = 'P' PAYMENT_STATUS_COMPLETE = 'C' PAYMENT_STATUS_FAILED = 'F' PAYMENT_STATUS_CHOICES = [ (PAYMENT_STATUS_PENDING, 'Pending'), (PAYMENT_STATUS_COMPLETE, 'Complete'), (PAYMENT_STATUS_FAILED, 'Failed') ] cart = models.ForeignKey(Cart, on_delete=models.CASCADE, null=True) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) entry_date = models.DateField() total_price = models.IntegerField() payment_status = models.CharField( max_length=1, choices=PAYMENT_STATUS_CHOICES, default=PAYMENT_STATUS_PENDING ) My question is: How can I get a particular Cart record from the Reception model? I tried using this serializer: class ReceptionSerializer(serializers.ModelSerializer): class Meta: model = Reception fields = ['id', 'customer', 'entry_date', 'payment_status', 'cart'] but it only returns the id of a cart. I want to return the whole object of that specific cart. How can I do that? -
Django Create object from within a model?
I'm developing a Django app part of which will be IP address allocation. As part of this I would like to be able to give user a list of available IP addresses which will be assigned to a ForeignKey (an object). I can use "ipaddress.ip_network('192.168.1.0/24').hosts()" to get a list of available hosts within a subnet, question is: How would I assign it to say "available_ips" field? Also, how would I then assign a particular IP from this block to an object? Would I need another class for IP object and create them as part of "IPBlockAllocation" maybe? Any advise would be much appreciated. SUBNET_MASK = ( (24, 24), ) IP_BLOCK_ROLE = ( ('Select', 'Select'), ('WAN', 'WAN'), ('LAN', 'LAN'), ('MGT', 'MGT') ) class IPAddressAssignment(models.Model): parent_block = models.ForeignKey( 'IPBlockAllocation', null=True, on_delete=models.CASCADE) address = models.GenericIPAddressField( blank=True, null=True, unique=True, validators=[validate_ipv4_address]) assigned_interface = models.ForeignKey( DeviceInterfaces, null=True, on_delete=models.CASCADE) class IPBlockAllocation(models.Model): name = models.CharField(unique=True, max_length=255) prefix = models.GenericIPAddressField( blank=True, null=True, unique=True, max_length=12) mask = models.IntegerField(choices=SUBNET_MASK) role = models.CharField( max_length=10, choices=IP_BLOCK_ROLE, default='Select') -
How to dynamically update prices for menu website? [closed]
I would like to publish a website that hosts menus for different restaurant branches. What would be good way to do publish this? Bearing in mind occasional price changes - does this mean taking the website down and re-deploying or is there a way I can dynamically update item prices? Hosting providers/CMS tools appreciated I have written the website using basic html/css/js so far.. I have only used django to host a website on the local loopback address. I am determined to learn more. -
Forbidden You don't have permission to access this resource. Apache2 with mod-WSGI django
404 Forbidden Apache/2.4.54 (Debian) Server at domainname.com Port 80 i cannot access my django web application on sever. i tried almost every possible solution but it don't work for me Django 3.2 Apache2 2.4 project-directory-path ------> /home/admin/toktobot/chatbot apache status is ok sudo apt-get install apache2 sudo apt-get install libapache2-mod-wsgi-py3 /etc/apache2/sites-available/django_project.conf <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html # ServerName domainname.com # # serverAlias www.domainname.com # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/admin/toktobot/chatbot/static <Directory /home/admin/toktobot/chatbot/static> Require all granted </Directory> <Directory /home/admin/toktobot/chatbot/chatbot> … -
Creating WebUI for sysadmin scripts
Yes, my question may sound very vague, incomplete. Beginner to webui developement. Looking for An interactive WebUI for SysAdmin tasks: What I have now? a lot of Ansible tasks, playbooks, bash scripts, python scripts for sysadmin tasks. Some of them can be stored locally(in laptop or in any location) Some of them can be placed only where it is kept and need to run from there. What I am trying to achieve? I would like to add a WebUI application to support these scripts. Don't want to edit the scripts and provide the values everytime through SSH and that usual execution like ./script.sh & python mypy.py. Once of the Example task: Have backups stored in S3 and onpremise locations. Importantly, Database and some miscellaneous things. Currently I am running some bash scripts, python scripts to restore them. (need to modify some variable depends on the selected backup) currently it shows what we have in S3 and we need to choose a backup date and list of archives and modify the restore script. So I was thinking, why not read from s3 and other backups locations, list items as checkboxes, execute will run the current scripts and everyone is happy. while … -
Basic query in django graphql doesn't work with relational models
This is my models.py class Player(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) username = models.CharField(max_length=25) class Challange(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) status = models.CharField(max_length=25, choices=StatusChoice.choices) from_player = models.ForeignKey(Player, related_name='my_challenges', on_delete=models.SET(get_sentinel_user)) to_player = models.ForeignKey(Player, related_name='challanges', on_delete=models.SET(get_sentinel_user)) schema.py class ChallangeType(DjangoObjectType): class Meta: model = Challange fields = ['id', 'status', 'from_player', 'to_player'] class Query(graphene.ObjectType): challanges = graphene.List(ChallangeType) def resolve_challanges(root, info): user = info.context.user return Challange.objects.filter(to_player=user.player, status=StatusChoice.WAITING) schema = graphene.Schema(query=Query) I want to get challenges concerns logged user, everything work when I demand 'id' and 'status' fields, but when I try add "from_player" or "to_player" I recive error "Cannot query field 'from_player' on type 'ChallangeType' Also, this fields(from_player, to_player) doesn't show us hints while writing. -
How can I configure these multiple slugs in my urls and views: Django
I've been trying to configure my urls and views for this password safe app a site can have many accounts, and to edit an account I plan to use this url config: home/[sitename]/[accountusername]/edit/. but its bringing errors. How do I go about this? My views.py: class SiteDetailView(DetailView): model = Site template_name = "site_detail.html" class SiteDeleteView(DeleteView): model = Site template_name = "site_delete.html" success_url = reverse_lazy("home") class SiteEditView(UpdateView): model = Site template_name = "site_edit.html" fields = ("siteName",) class AccountDeleteView(DeleteView): model = Account template_name = "account_delete.html" # def get_success_url(self): # return reverse_lazy("site_detail", kwargs={"slug": self.object.slug}) class AccountEditView(UpdateView): model = Account template_name = "account_edit.html" fields = ( "username", "password", ) my urls.py: from django.urls import path from .views import ( IndexView, HomePageView, SiteDetailView, SiteDeleteView, AccountDeleteView, AccountEditView, SiteEditView, ) urlpatterns = [ path("home/<slug:slug>/edit/", SiteEditView.as_view(), name="site_edit"), path( "home/<slug:slug>/<slug:slug_field>/edit/", AccountEditView.as_view(), name="account_edit", ), path( "home/<slug:slug>/<slug:slug_field>/delete/", AccountDeleteView.as_view(), name="account_delete", ), path("home/<slug:slug>/delete/", SiteDeleteView.as_view(), name="site_delete"), path("home/<slug:slug>/", SiteDetailView.as_view(), name="site_detail"), path("home", HomePageView.as_view(), name="home"), path("", IndexView.as_view(), name="index"), ] my models: from django.db import models from django.urls import reverse from django.conf import settings from django.template.defaultfilters import slugify class Site(models.Model): siteName = models.CharField(max_length=200) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) slug = models.SlugField(null=False, unique=True) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.siteName def get_absolute_url(self): return reverse("site_detail", kwargs={"slug": self.slug}) def save(self, … -
Django error Broken pipe from ('127.0.0.1', 1628) when exporting to pdf using Xhtml2pdf
I have django a view that exports records using the xhtml2pdf library, however I have observed that the view keeps refreshing several times as my pdf function processes the request. Also, this behavior keeps reloading the view for a number of times until the file is ready for export. This is potentially harmful since the view queries data in bulk to be loaded onto the pdf. The error I am getting from the terminal is: Broken pipe from ('127.0.0.1', 1314) I read somewhere that this could be as a result of the browser closing and opening the connection but I tested on another view loading a page and delayed the response but it did not happen as above. This is my views.py: @login_required(login_url='/') @user_passes_test(validate_all_view()) def export_assets(request): if request.method == 'POST': checkbox_list = request.POST.getlist('id[]') if not len(checkbox_list) > 0: messages.error(request, "You must select at least one row to export.") return redirect('view_active_assets') queryset = Assets.objects.filter(id__in=checkbox_list)[:10000] if 'excel' in request.POST: return process_excel_export(queryset) if 'pdf' in request.POST: return process_pdf_export(request, queryset) else: return redirect('view_active_assets') render function: def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("UTF-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None Process pdf function: def process_pdf_export(request, … -
Pytest Fixture to use sqlite file based DB for test?
I'm using pytest and pytest-django to test a Django project. I have test_settings.py that I use in order to use in-memory databases. It is very simple and looks like this: from .settings import * # Set up in memory databases for testing purposes DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", }, "other_db": { "ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:", }, } My pytest.ini is equally simple: [pytest] DJANGO_SETTINGS_MODULE = ic_project.test_settings python_files = tests.py test_*.py *_tests.py There are a few spots where I would like to test using an actual .sqlite3 file - not in memory. So I tried writing the following fixture: @pytest.fixture(scope="function") def file_based_db(settings): """Generator to create a file based database for testing""" settings.DATABASES["default"]["TEST"] = { "ENGINE": "django.db.backends.sqlite3", "NAME": "default_db.sqlite3", } settings.DATABASES["other_db"]["TEST"] = { "ENGINE": "django.db.backends.sqlite3", "NAME": "other_db.sqlite3", } So a test I'd like to use this 'file_based_db' on would look something like this: @pytest.mark.usefixtures("file_based_db") class ThingForm(TransactionTestCase): def setUp(self): self.thing = Thing.objects.create(name="thing1") def test_empty_form_fields(self): form = MyForm() self.assertIn("created_by", form.fields) self.assertIn("deleted_at", form.fields) self.assertIn("updated_by", form.fields) breakpoint() However when I run this I get the following error: return [ alias for alias in connections if alias in cls.databases and ( > include_mirrors or not connections[alias].settings_dict['TEST']['MIRROR'] ) ] E KeyError: 'MIRROR' Ultimately as … -
How to add same variable in different files and folders?
I am working on a Django project that has lots of different files and folders. For processing there is a queue that has different queue names depending on the usage. For changing the name of the queue one must go through every single files in every single folder and change the name 1 by 1 manually. How can i use a global variable that can be assessed from anywhere in the program even directories that are beyond and below the current file? So that i need to change only the variable name and every queue name in the project will get changed -
Convert data of type time inside array to int or float. Error: unsupported operand type(s) for +: 'int' and 'numpy.str_'
def ProdGrafico(request): ## Dados Media Duracao do Forno mediaForno = Relatorioresumido.objects.all() divideForno = len(mediaForno) listMediaForno = [] for x in range(int(divideForno)): y = mediaForno[x].duracaoforno y = datetime.strptime(y, '%H:%M:%S') listMediaForno.append(y) try: mediaForno = listMediaForno[0] + sum((listMediaForno_i - listMediaForno[0] for listMediaForno_i in listMediaForno), timedelta(0)) / len(listMediaForno) print(mediaForno) except ZeroDivisionError: mediaForno = 00 -
how do i serve media files when going through a url? django
i have a django project where i need to serve media files. i have one url that serving media files works on and one the doesn't. the one that doesn't has a search/ placed in front of it and i assume thats the reason it can't find the media files. i use the search url in other parts of my program and don't want to break the other parts my changing it. is there anyway i could stop the search/ from appearing without changing the url pattern? blue is when the media files are collected and yellow is when its not working -
NameError at /post/category/
I catch an error, where exactly I found it, but I don’t understand what to do. models.py 'from django.contrib.auth.models import User from django.db import models class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, blank=True, null=True) title = models.CharField(max_length=255) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) views = models.PositiveIntegerField(default=0) like = models.PositiveIntegerField(default=0) enabled = models.BooleanField(default=False) category = models.ForeignKey( "Category", on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return f'{self.title}' class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.PROTECT, blank=True, null=True) author = models.ForeignKey( User, on_delete=models.CASCADE, blank=True, null=True) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True) def __str__(self): return f'{self.text}' class Category(models.Model): title = models.TextField() enabled = models.BooleanField(default=False) def __str__(self): return f'{self.title}' veiws.py 'from blog.forms import PostForm from blog.models import Post from django.http import Http404 from django.shortcuts import get_object_or_404, redirect, render # Create your views here. def post_list(request): posts = Post.objects.filter(enabled=True) return render(request, "blog/post_list.html", {"posts": posts}) def post_detail(request, post_pk): post = get_object_or_404(Post, pk=post_pk) post.views += 1 post.save() return render(request, "blog/post_detail.html", {"post": post}) def post_new(request): if request.method == "GET": form = PostForm() return render(request, "blog/new_post.html", {"form": form}) if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): post = form.save(commit=False) post.author = request.user post.save() return redirect('post_detail', post_pk=post.pk) def post_edit(request, post_pk): post = Post.objects.filter(pk=post_pk).first() if not post: raise Http404("Post not found") if request.method == "GET": … -
How to save multipart / formdata turned into a QueryDict using Django REST Framework (DRF) and ModelSerializer
I am sending multipart/formdata from a Next.js API and I can format the data whichever way I want but I am struggling to get the right format. For now, I have the following formdata: <QueryDict: { 'name': ['Test Product'], 'brands[0]': ['1'], 'brands[1]': ['2'], 'option_types[0]': ['1'], 'product_variants[0]option_values[0]': ['1'], 'product_variants[0]option_values[1]': ['2'], > My ModelSerializer is not accepting the way I am specifying the lists/arrays. For instance, if I try to do: def validate_option_types(self, data): print(data) return data I get an empty list meaning the format for option_types list is wrong and the same applies for the product_variants and option_values. I am simply passing the QueryDict obtained from request.data as follows: def create(self, request, *args, **kwargs): serializer = ProductDetailAdminSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, status=400) The serializer and everything else are working fine if I use a JSON version of the QueryDict above and the JSON content-type. So to summarise my question, what is the correct QueryDict format (specifically for fields which represent lists) for the DRF ModelSerializer? Or is there an extra step that I am missing in getting the QueryDict to the format expected by the model serializer. -
Can graphene resolver return Float instead of String for django Decimal field?
Graphene's resolver returns my django model Decimal field as a string (e.g. "8.33" instead of 8.33). I want to receive it as a float. Is there some way to do this? My code is as follows: models.py class Toy(models.Model): name = models.CharField(max_length=50) price = models.DecimalField() queries.py class ToyType(DjangoObjectType): class Meta: model = Toy fields = ('name', 'price') class ToyQuery(graphene.ObjectType): first_toy = graphene.Field(ToyType) def resolve_first_toy(self, info): return Toy.objects.first() And my query and result are: query { firstToy{ name price } } result { "data": { "name": "BuzzLighYear", "price": "19.95" } } Instead, I would like to receive: { "data": { "name": "BuzzLighYear", "price": 19.95 } } Do I have to write a custom resolver for the price field, or is there a more elegant way to do this with a setting? -
NameError at / name 'RequiredDocument' is not defined
All the code works perfectly fine on the localhost and the same code gives the above error on a hosted website with the same code. I reran migrations also but still got the same error. -
How can I use Linkify with Django_tables2
I have read a few similar questions and all the docs I can find on this but I am still not able to understand the solution. I have built my model to have a player, the text description of a keyboard and a url to it. I want to show in a table the player, the keyboard and i want to have the keyboard text have the url column embedded within it. Any help would be appreciated. Models.py: class player_hardware(models.Model): Player = models.TextField(blank = False, primary_key = True) keyboard = models.TextField(blank = True, max_length = 200) keyboard_url = models.TextField(blank = True, max_length = 200) Views.py: class PlayerListView(SingleTableView): model = player_hardware table_class = PersonTable template_name = 'application/playerlist.html' Tables.py class PersonTable(tables.Table): class Meta: model = player_hardware template_name = "django_tables2/bootstrap4.html" fields = ("Player", "keyboard") -
Django exclude one object cause more to be excluded
that's the weirdest bug I've ever faced since I started using Django I've a queryset with some corrupt data that needs to be excluded, when printing the queryset length it prints 97 and when prints the corruptdata queryset it's 2 so the result must be 95, but what I get is only 70!! here's my code qs = model.objects.filter( query, **sku_filter ).values( 'sku', 'sku__asin', 'sku__title', ).order_by( '-report_date', 'sku', ).annotate( in_inbound=Coalesce( LedgerQuery.in_inbound_subquery, Value(0) ) ).annotate( fnsku=F('fnsku'), action=F('sku__reconciliation_activity__action'), case_number=F('sku__reconciliation_activity__case_number'), is_being_manually_reconciled=F('sku__reconciliation_activity__is_being_manually_reconciled'), missing_subquery_count = Count(missing_subquery_count), missing=Subquery( queryset=missing_subquery ), available=Sum( 'ending_warehouse_balance', filter=Q(disposition='SELLABLE') ), total_units=Sum( F('ending_warehouse_balance') + # Available + Unsellable units in all the countries warehouses Abs('in_transit_between_warehouses') + # Reserved Component 1 Abs('customer_shipments') # Reserved Component 2 ) + F('missing') + F('in_inbound'), # it's important to put out the missing from the Sum, otherwise # the result will be missing * grouped by rows main_image_link=Subquery( queryset=main_image_link_subquery ) ) ##prints 97 print(qs.count()) ##prints 70 print("c1", qs.filter( ~Q( action=ReconciliationActivity.ActionChoices.NO_ACTION, missing__gte=1 ) ).count() ) ##prints 2 print( qs.filter( action=ReconciliationActivity.ActionChoices.NO_ACTION, missing__gte=1 ).count() ) I tried to convert it to sql to be easier for debug but it was more then 45k of words and eventually I couldn't find anything wrong with it -
POST with button in django - How I get the objects id to my project views?
I'm working on the messaging system, in template: {%for i in message%} <table> <tr> <td colspan="3" style="width: 80%"><b>{{i.subject}}</b></td> </tr> <tr> <td colspan="3" style="width: 80%">{{i.message}}</td> </tr> </table> <div> <div style="padding-top:5px; padding-right:5px; text-align:right"> <div>{{i.messagedate}} - {{i.messagehour}} - <a type="submit" name="delete" value="{{i.id}}">Delete message!</a>{%endfor%} in my views: if request.method == "POST"and 'delete' in request.POST: messageid= request.POST['delete'] message.objects.filter(id=messageid).update(delete=1) I want to delete that message by getting the message id from the form. How can I do it? I'm deleting it using a button, but it happens when the message id is instead of delete the text of the button. I tried type="hidden" but then it takes the id of the latest message in the database to the views, not the id of that message. -
as_crispy_field got passed an invalid or inexistent field
im getting this error as_crispy_field got passed an invalid or inexistent field every time im trying to use as_crispy_field with forms here is my code models.py class Customer_Email(models.Model): subject=models.CharField(max_length=50,null=True,blank=True) message=models.TextField(max_length=1000,null=True,blank=True) file_upload=models.FileField(null=True,blank=True) sender=models.ForeignKey(User,on_delete=models.CASCADE ,null=True,blank=True) company=models.ForeignKey(Customer,on_delete=models.CASCADE ,null=True,blank=True) date=models.DateTimeField(auto_now=True) views.py def send_email(request,id): customer=get_object_or_404(Customer,pk=id) form=Customer_Email_Form(request.POST) customers=Customer.objects.all() context={"customer":customer,"email_form":form,"customers":customers} if request.method == 'GET': return render(request,'crm/email_form.html',context) if request.method=='POST': if form.is_valid(): form.save() messages.success(request,"Email Sent") return render(request,'crm/listing.html',context) return render(request,'crm/email_form.html',context) html {% load crispy_forms_tags %} <form class="" method="POST"> {% csrf_token %} <div class="form-group m-2"> <label>Subject</label> {{email_form.subject|as_crispy_field}} </div> <div class="form-group m-2"> <label>Message</label> {{email_form.message|as_crispy_field}} </div> <div class="form-group m-2"> <label>Uplaod</label> {{email_form.file_upload|as_crispy_field}} <span class="color-secondary">you can attach 2M files (pdf,doc)</span> </div> {{email_form.company|as_crispy_field}} {{email_form.sender|as_crispy_field}} <button class="btn btn-primary btn-lg mt-5" type="submit" hx-post="email_form/p={{customer.id}}" hx-target="#crm-list" data-dismiss="modal" >Send Email <i class='bx bx-mail-send bx-xl'></i></button> </form> forms.py class Customer_Email_Form(forms.ModelForm): class Meta: model=Customer_Email fields=['subject','file_upload','message','sender','company'] i have tried to change it to forms.Form but it gives me the same error i dont know what excactly i should do and im new to it