Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why is my for loop not working in django views
Why is my for loop not working in django? i keep getting AttributeError: 'list' object has no attribute 'items' @csrf_exempt def testfunc(request): if request.method == 'POST': json_data = json.loads(request.body) for d,v in json_data.items(): print(d) return JsonResponse(x,safe=False) -
Is it possible to add one mixin to every view in file automatically?
As in title. Is there a way to add, f.e. UserPassesTestMixin to every view in file without inheriting it in every one of them? Let's say it would look like this: Mixin: UserPassesTestMixin Test: def test_func(self): # Some condition # .../views.py class FirstSampleView(SomeView): # View code class SecondSampleView(SomeView): # View code My target is that FirstSampleView, SecondSampleView and every other view in this file would have automatically my desired Mixin with according test_func. -
how to insert data to database from view in django
I'm have page with form for generate cards with two buttons "generate" and "send to db". After generate I'm want put this generated data to db by button page from the same page. But when button generate pressed - django render page and context not available again (in this variable stored my generated data). How i'm can implement this - insert data to database from view in django? Thanks! views.py def generate(request): if request.method == "POST": if 'generate' in request.POST: form = GenerateCards(request.POST) if form.is_valid(): series = request.POST["series"] quantity = request.POST["quantity"] how_long = request.POST["how_long"] cards = card_generator(series, quantity, how_long, 0) context = {'form':form} context.update({'cards':cards}) return render (request, "wasite/generate.html", context) if 'send_to_db' in request.POST: print(request.POST) form = Card for i in context['cards']: card = form.save(commit=False) series = i[0] number = i[1] status = i[2] period = i[3] card.save() return render(request, "wasite/generate.html", context) else: form = GenerateCards() return render(request, "wasite/generate.html", {'form':form}) urls.py path("generate/", views.generate, name="generate"), path("generate/ready", views.generate, name="ready"), path("generate/send_to_db", views.generate, name="send_to_db"), generate.html {% extends 'wasite/cards.html' %} {% block title %} Create New List {% endblock %} {% block content %} <h3>Genearte a New Cards</h3> <br> <form method="post" action="ready" class="form-group"> {% csrf_token %} {{form.as_p}} <div class="input-group mb-3"> <div class="input-group-prepend"> <button name="generate" type="submit" class="btn … -
Adjustable Forloop Range - HTML
I have an html file in my django templates that contains a forloop. I need to to have a range on the forloop that basically says the forloop will only loop through the first 10 attributes. The complication arrises when I need the range to be adujstable. I need something like a number input that keeps a varaible and then only loops through that many attributes in the forloop. I have been on it for a few days and havent made too much progress. I have worked with simple forloop ranges but havent found a way to make them adjustable. This is the forloop I have been working with. {% for post in filter.qs %} {% if post.image %} <img class="pdf_field_img" src="{{ post.image.url }}"/> {% else %} {% endif %} <div class="title">Morgan Hall</div> <div class="inspection_num">Inspection #</div> <div class="inspect_num">{{ post.count_building }}</div> {% endfor %} -
returned json response is undefended django
I'm trying to load my json response into my template but when i check it into my console returns undefended ! @login_required def booking_detail_lists(request,id): obj = get_object_or_404(Booking.objects.annotate(no_persons=Count('takes_by')),id=id) bookingvisitors = BookingVisitor.objects.filter(booking=obj) doc = Document.objects.filter(booking=obj) documents = [] for i in doc: documents.append({ 'source':i.docs.url }) visitors = [] for i in bookingvisitors: visitors.append({ 'full_name':i.visitor.full_name, 'reason':i.reason, 'check_in_vis':i.check_in_vis.strftime("%Y-%m-%dT%H:%M"), 'check_out_vis':i.check_out_vis.strftime("%Y-%m-%dT%H:%M"), 'admin':i.admin.username, 'date':i.date.strftime("%Y-%m-%dT%H:%M") }) data = { 'check_in':obj.check_in.strftime("%Y-%m-%dT%H:%M"), 'check_out':obj.check_out.strftime("%Y-%m-%dT%H:%M"), 'taker':obj.taker, 'phone':obj.phone, 'no_person':obj.no_persons, 'id':obj.id, 'takes_by':visitors, 'images':documents, } json_data = json.dumps(data) return render(request,'booking/booking_detail.html',{'data':json_data,'obj':obj,'id':obj.id}) urls.py path('ajax/booking/<int:id>',booking_detail_lists , name='booking_detail_lists'), my html template and ajax $.ajax({ type:'GET', url:"{%url 'booking:booking_detail_lists' id=2222 %}".replace(/2222/,parseInt({{id}})), success:function(data){ console.log(data.data) } }) <!--some html tags--> but in the browser console returns undefinedbut when i just type {{data}} it show as i expected ?! thank you for your recommendation .. -
Gather values from checkboxes, multiple options selected
I am building a python/django application. I have an Exercise table, with 3 choices: body part, equipment, and category. I have used ajax to get all exercises. However, before I show any exercise, I want to filter them. On I want to be able to select multiple options in body part, equipment, and category. For example, I want all the exercise that targets the body parts back, abs, and core. Right now, I am able to only search for one body party part at a time in JS, but I can still select multiple options. if(resultsBox.classList.contains('not-visible')){ resultsBox.classList.remove('not-visible'); } sendSearchData(e.target.value); })``` this is my JS code. the sendSearchData is the function that calls my ajax. ```<div class="dropdown" id="body_part"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false"> <img src="{% static 'img/bodypart-icon.png' %}" Alt="Body Part Icon" style="height: 25px; color: black"> Body Part </button> <ul id="body_part_data_box" class="dropdown-menu" aria-labelledby="dropdownMenuButton"> {% for choice in filter.form.body_part %} <li class="dropdown-item"> <input type="checkbox" id={{choice.choice_label}} value = {{choice.choice_label}}" name="body_part[]" class="body_part"> {{choice.choice_label}}</li> {% endfor %} </ul> </div>``` This is the HTML code for how I created my drop down menu. For my models, I have pre-defined all my choice options. My question, how to I get all the exercises for the … -
How to implement a basic size file verification in the below code
I want to implement a file size check directly in this views.py function. It is possible? I want to limit the upload to 10M. class PageView(TemplateView): template_name = 'page.html' def my_fuctions(request): saida = [] if str(request.user) != 'AnonymousUser': if request.method == 'POST': person_resource = PersonResource() try: new_person = request.FILES['myfile'] if not new_person.name.endswith('xlsx'): messages.info(request, 'Wrong format.') return render(request, 'page.html') imported_data = new_person = request.FILES['myfile'] Curadoria.verifica_web(Curadoria, imported_data, saida) except KeyError: messages.info(request, 'Por favor, carregue o arquivo de dados.') context = { 'saida': saida, 'header': 'saida', } return render(request, 'page.html', context) -
Django collection of instances of same model
I'm new to Django I'm currently using django 3.2.6. I want make multiple instances of route_stop model and store in SchoolRouteStop.route_graph model.I don't want use ForeignKey because i want to make somthing like like nested dict. from django.db import models class geo_fence(models.Model): radius = models.FloatField() class geo_location(models.Model): latitude = models.FloatField() longitude = models.FloatField() class address(models.Model): entity = models.fields.CharField(max_length=100) apt_plot = models.fields.CharField(max_length=100) street = models.fields.CharField(max_length=100) city = models.fields.CharField(max_length=100) state = models.fields.CharField(max_length=2) #state name in short code zip_code = models.fields.IntegerField() class route_stop(models.Model): # this for multiple bus stops route_stop_id = models.fields.IntegerField() school_id = models.fields.CharField(max_length=100) route_number = models.fields.CharField(max_length=100) school_route_stop_uuid = models.fields.CharField(max_length=100, primary_key=True) registered_arrival_time = models.TimeField() time_from_src = models.FloatField() is_school = models.BooleanField(default=False) geo_fence = models.ForeignKey(geo_fence, on_delete =models.CASCADE) geo_location = models.ForeignKey(geo_location, on_delete = models.CASCADE) address = models.ForeignKey(address, on_delete = models.CASCADE) class SchoolRouteStop(models.Model): school_id = models.CharField(max_length=100) school_route_number = models.IntegerField() route_type = models.CharField(max_length=2) route_id = str(school_id)+'_'+str(school_route_number)+str(route_type) route_graph= models.ForeignKey(route_stop,related_name='School', on_delete = models.CASCADE) # Create your models here. -
Show Django model/database as HTML table
Is there a way to show this model: # models.py class Classes(models.Model): Team = models.CharField(default='-', max_length=15) Name = models.CharField(default='-', max_length=15) ClassCode = models.CharField(default='-', max_length=10) MissingClass = models.CharField(default='-', max_length=15) MakeUpClass = models.CharField(default='-', max_length=15) Note = models.CharField(default='-', max_length=25) TuitionPaid = models.CharField(default='Pending', max_length=10) class Meta: verbose_name_plural = "Classes" As an HTML table, preferably without third party apps? I've got an empty placeholder template under the same app. All the urlpatterns stuff is linked up already. (I have a views.py file, it's just not in the image, the views copy.py file is backup -
Django url with params, don't know how to test
can anyone give help me how to test the following url in django? path('<int:id>/update/', MyUpdateView.as_view(), name='my-update') So far I have this, but it does not contains the param, therefore it fails. def test_url(self): url = reverse('my-update') self.assertEquals(resolve(url).func.view_class, MyUpdateView) Thank you in advance! -
FormSet with different Form value
I would like to have several form according to the day. That's why using FormSet object is a good idea. Each Form is dynamically changed according to the day. I would like to display several Form, each of them with different day. This is my Form : class AvailabilitiesForm(forms.Form): time_slot = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple) def __init__(self,*args,**kwargs): date = kwargs.pop('date') super().__init__(*args,**kwargs) ava_value_timeslots = ((key, val) for key, val in dict(Appointment.TimeSlot.choices).items() if int(key) not in list(Appointment.objects.filter(date = date).values_list('time_slot', flat = True))) self.fields['time_slot'].choices = ava_value_timeslots the ava_value_timeslots variable returns a couple like this : ('0', '9:00 - 09:30'), ('1', '9:00 - 09:30'), ... ('26', '22:00 – 22:30') Is this possible to pass argument in FormSet to have different day of each form like this ? def chooseAvailabilities(request): dates = [ (datetime.date.today() + datetime.timedelta(days=i)).strftime("%Y-%m-%d") for i in range(7)] AvailabilitiesFormSet = formset_factory(AvailabilitiesForm, extra = 7, date = dates) return render(request, 'panel/choose_availabilities.html', {'form' : AvailabilitiesFormSet}) This is actually my view but for one form... : def chooseAvailabilities(request): date_3 = (datetime.date.today() + datetime.timedelta(days=3)).strftime("%Y-%m-%d") return render(request, 'panel/choose_availabilities.html', {'form_date_3' : AvailabilitiesForm(date = date_3)}) -
The current path, imgupload/imageprocess, didn't match any of these
I'm trying to create a Django app but I'm stuck at this error. Using the URLconf defined in my_first_site.urls, Django tried these URL patterns, in this order: imgupload [name='home'] imgupload imageprocess [name='imageprocess'] admin/ here are my files: home.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>My Home</title> </head> <body> <form action="/imgupload/imageprocess" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input id="image" type="file" name="image"/> <input type="submit" value="submit"> </form> </body> </html> urls.py (This one is from project i.e. my_first_site) from django.contrib import admin from django.urls import path,include urlpatterns = [ path('imgupload',include('imgupload.urls')), path('admin/', admin.site.urls), ] urls.py -- (this one is from webapp i.e. imgupload) from django.contrib import admin from django.urls import path,include from . import views urlpatterns = [ path('',views.home, name='home'), path('imageprocess', views.imageprocess, name='imageprocess'), ] views.py from django.shortcuts import render # Create your views here. def home(request): return render(request,'home.html') def imageprocess(request): return render(request,'result.html') result.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Result page</title> </head> <body> <h1>This is result page</h1> </body> </html> This is the error Django giving me -
Django Model not accepting field
I created the following Model: class dv_model(models.Model): Defect_Area_dv = models.CharField(_('Defect Area dv'), max_length=200 ) Key_Driver_dv = models.CharField(_('Key Driver dv'), max_length=200) Sub_Key_Driver_dv = models.CharField(_('Sub Key Driver dv'), max_length=200 ) QS_Login_dv = models.CharField(_('QS Login dv'), max_length=200) QS_Name_dv = models.CharField(_('QS Name dv'), max_length=200) Status_dv = models.CharField(_('Status dv'), max_length=200) Correct_Associate_Action_dv = models.CharField(_('Correct Associate Action dv'), max_length=200) Correct_investigator_Action_dv = models.CharField(_('Correct investigator Action dv'), max_length=200) Action_Correctly_Captured_dv = models.CharField(_('Action Correctly Captured dv'), max_length=200) Audit_Outcome_dv = models.CharField(_('Audit Outcome dv'), max_length=200) Defect_Area_Investigator_dv = models.CharField(_('Defect Area Investigator'), max_length=200) Document_Name_dv = models.CharField(_('Document Name dv'), max_length=200) Document_Type_dv = models.CharField(_('Document Type dv'), max_length=200) Type_of_Audit_dv = models.CharField(_('Type of Audit dv'), max_length=200) If_Correctly_Captured_No_dv =models.CharField(_('If Correctly Captured No dv'), max_length=200) Country_dv = models.CharField(_('Country dv'), max_length=200) Region_dv = models.CharField(_('Region dv'), max_length=200) Metric_name_dv = models.CharField(_('Metric name dv'), max_length=200) def __str__(self): return f"Data_Val: {self.Defect_Area_dv}-{self.Key_Driver_dv}-{self.Sub_Key_Driver_dv}-{self.QS_Login_dv}-{self.QS_Name_dv}-{self.Status_dv}-{self.Metric_name_dv}-{self.Correct_Associate_Action_dv}-{self.Correct_investigator_Action_dv}-{self.Action_Correctly_Captured_dv}-{self.Audit_Outcome_dv}-{self.Defect_Area_Investigator_dv}-{self.Document_Name_dv}-{self.Document_Type_dv}-{self.Type_of_Audit_dv}-{self.If_Correctly_Captured_No_dv}-{self.Country_dv}-{self.Region_dv}" Everything worked fine, until I decided to add these two fields: Metric_name_dv = models.CharField(_('Metric name dv'), max_length=200) Defect_Area_Investigator_dv = models.CharField(_('Defect Area Investigator'), max_length=200) After adding these two fields and running makemigrations and migrate i kept on getting this error: When looking at sqlite3, i dont see the fields: Metric_name_dv & Defect_Area_Investigator_dv: What could I be missing? I tried to clear all past migrations and that didnt work, so i reset it back to normal. Here … -
Display media images from directly Digitalocean app platform
I hosted web app to digital ocean app platform, but media files aren't displaying at all, is there any way to serve that from digital ocean and not to use aws. models file: class Projects(models.Model): title = models.CharField(max_length=50) description = models.TextField() image = models.ImageField(upload_to='images/',null=True) created_at = models.DateTimeField(auto_now=True) def __str__(self): return self.title class Meta: ordering = ['title'] view file: class ProjectList(generic.ListView): model = models.Projects url: urlpatterns = [ path('', views.ProjectList.as_view(), name='all'), path('postmodernism/', include('postmodernism.urls', namespace='postmodernism')), path('newstories/', include('newstories.urls', namespace='newstories')), ] template: {% extends 'projects/projects_base.html' %} {% block projects_content %} {% for projects in projects_list %} {% include 'projects/_projects.html' %} {% if projects.title == 'პოსტ მოდერნიზმი' %} <a href="{% url 'projects:postmodernism:postindex' %}"><img src="{{ projects.image.url }}" alt="postmodernism" width="100" height="100"></a> {% endif %} {% if projects.title == 'ამბების ახლებური განვითარება' %} <a href="{% url 'projects:newstories:all' %}"><img src="{{ projects.image.url }}" alt="newstories" width="100" height="100"></a> {% endif %} {% endfor %} {% endblock %} -
Django - Have a user logged in authentication check on every REST API call
I have this code of 2 views in Django. You will notice that each REST API call has a verify_login() function call that ensures that the request contains a verified JWT token. I'm wondering if there's a better way to implement this so that I don't have to have these lines specifically in every REST endpoint verify_response = verify_login(request) if verify_response not None: return verify_response I'm trying to follow the D.R.Y. (Do Not Repeat Yourself) principle of coding. It'd be nice if there was a cleaner way to represent this. I thought about maybe creating a module extending APIView that automatically has this and then all my Views extend that, but runs into the issue of having to call super().API_REQUEST() and then having to do the same if-statement check to see if it's None or not. class PostView(APIView): """ View for Post object * requires token authentication """ # Create post @swagger_auto_schema( request_body=PostSerializer, operation_description="Create a post object" ) def post(self, request): verify_response = verify_login(request) if verify_response not None: return verify_response serializer = PostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) # get all posts @swagger_auto_schema( operation_description="Get all posts from the DB" ) def get(self, request): verify_response = … -
How to determine the correct user to update or delete the post
I want to update and delete post and it is happening but now I want users to Update and delete a post only created by them. Strating from delete this is my delete function def delete_post(request , id): post=Post.objects.get(pk=id) if request.user==post.user: '''I think this if is not true even when the post is created by the same user who is requesting to delete it.''' post.delete() print("ok") return redirect("home") Now when click on delete post it returns to home page but the post remains same.it doesn't delete the post. -
Django Model Meta Ordering on Property
I am trying to tell Django to order my Host model based on a property but am getting the following error: app.Host: (models.E015) 'ordering' refers to the nonexistent field, related field, or lookup 'primary_hostname'. What's the correct approach to ordering based on a property like this? I want the queryset to be ordered by primary hostname which I define as the shortest hostname assigned to each host. models.py class Hostname(models.Model): name = models.CharField(max_length=settings.MAX_CHAR_COUNT, unique=True, blank=False, null=False) class Host(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) names = models.ManyToManyField(Hostname) class Meta: ordering = ['primary_hostname'] @property def primary_hostname(self): return self.names.annotate(text_len=Length('name')).order_by('text_len').first() def __str__(self): return "[Host object: id = {}]".format(self.id) def __repr__(self): return "[Host object: id = {}]".format(self.id) def __eq__(self, other): if isinstance(other, Host): return self.id == other.id return False def __hash__(self) -> int: return hash(self.id) def __lt__(self, other): return self.id < other.id def get_absolute_url(self): return '/host/{}'.format(self.id) -
Django: use a Foreignkey relationship for custom user model
I am writing a webapp where I want to have a general Person table to uniquely identify any person interacting with the website, e.g. to be able to comply to GDPR requests. Some Persons will should also be Users in the authentication sense. I'd like to use Person.email for the username. However, I cannot manage to make authentication / admin interface work. Simplified models: from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin class Person(models.Model): name = models.CharField(max_length=255, blank=False) email = models.EmailField(blank=False, unique=True) class User(AbstractBaseUser, PermissionsMixin): person = models.OneToOneField(Person, on_delete=models.PROTECT) USERNAME_FIELD = ...# what to put here? I found a very old Django issue that seems related: https://code.djangoproject.com/ticket/21832 Any idea, how to make this work with a foreign key to hold the basic user information? -
How to apply only to optional products using template tags
I want to import the code below using the template tag. I'd like to write a code for a product that has an option and a product that doesn't have an option. "If you don't have an option, launch the following code." How do I write this condition? views.py option_object = Option.objects.all() value_object = Value.objects.all() product = get_object_or_404(Product, product_code=id, slug=product_slug) Models.py class Product(models.Model): product_code = models.AutoField(primary_key=True) username = models.ForeignKey(Member, on_delete=models.CASCADE, db_column='username') category_code = models.ForeignKey(Category, on_delete=models.SET_NULL, null=True, related_name='products') name = models.CharField(max_length=200, db_index=True) slug = models.SlugField(max_length=200, db_index=True, unique=False, allow_unicode=True) image = models.ImageField(upload_to='products/%Y/%m/%d', blank=True) benefit = models.TextField() detail = models.TextField() target_price = models.IntegerField() start_date = models.DateField() due_date = models.DateField() created_at = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['product_code'] index_together = [['product_code', 'slug']] def __str__(self): return self.name def get_absolute_url(self): return reverse('zeronine:product_detail', args=[self.product_code, self.slug]) ordering = ['photo_code'] class Option(models.Model): option_code = models.AutoField(primary_key=True) name = models.CharField(max_length=32) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code') def __str__(self): return self.name class Meta: ordering = ['option_code'] class Value(models.Model): value_code = models.AutoField(primary_key=True) option_code = models.ForeignKey(Option, on_delete=models.CASCADE, db_column='option_code', null=True) product_code = models.ForeignKey(Product, on_delete=models.CASCADE, db_column='product_code', null=True) name = models.CharField(max_length=32, null=True) extra_cost = models.IntegerField(null=True) def __str__(self): return self.name class Meta: ordering = ['value_code'] I'd like to upload the code below only when it's a product without options. … -
Method Not Allowed (GET): and one keyerror
I know this error is because of not adding the 'GET' method but in my program I don't really get the point how I have to use that method in here. In here,I'am trying to add a favorite button in the page describing the car's details. So if I think iam right, the favorite button is embedded within the cardetails page. And when the 'favorite button is clicked, the post method is activated and straight to the method. There, I capture the 'POST' data named 'favorite' from the form .and i store it in the session. Then after every loading of the 'cardetail' page the method, loading the detail page will check whether, if this car is favorite or not, and pass adequate Boolean to HTML. So if only 'POST' is getting excuted then, why 'GET'? and after initializing the 'GET' I still got the Key error for the word 'favorite', in the get_context_data, of accessing the favorite ** This is my html {% if is_favorite %} <h2>This is my favorite</h2> {% else %} <form action="{% url 'favorite' %}" mthod='POST'> {% csrf_token %} <input type="hidden" value={{showroom.id}} name="favorite"> <button> Make This Favorite </button> </form> {% endif %} ** This is my … -
Maximize selection in MultipleChoiceField in Django?
Is there a way to maximize the selected elements in a MultipleChoiceField form ? -
i want to render a html invoice to pdf in django which module is best
i want to render a html invoice to pdf in django which module is best plz help!!! -
trying to send email with python and django
So I am trying to send email with python in a django view problem is everything inside my own server localhost is ok but in production it just dont like to work and I dont know why here is the code @api_view(["PUT"]) @permission_classes([IsAuthenticated]) def updateOrderToPaid(request, pk): order = Order.objects.get(taransId=pk) orderItems = OrderItem.objects.filter(order=order).all() address = ShippingAddress.objects.get(order=order) smtp_server = "smtp.gmail.com" port = 465 sender_email = "MYGMAIL" password = "MYPASSWORD" receiver_email = "RECEIVERGMAIL" message = MIMEMultipart("alternative") message["Subject"] = "DONE" message["From"] = sender_email message["To"] = receiver_email context = ssl.create_default_context() text = """\ ITS WORKING """ html = """\ <html> <body> <p class="text-danger">Done!</p><br> <ul>\n """ html += "\n".join(["<li>" + str(s) + "</li>" for s in orderItems]) html += f""" \n</ul> </body> </html>""" part1 = MIMEText(text, "plain") part2 = MIMEText(html, "html") message.attach(part1) message.attach(part2) data = { 'pin' : 'SOME_PIN', 'amount' : int(order.TotalPrice), 'transid' : order.taransId } try: response = requests.post('https://panel.aqayepardakht.ir/api/verify', data = data) if response.status_code == 200 and response.text == '1': order.isPaid = True order.paidAt = datetime.now() order.save() return Response({"message": "پرداخت با موفقیت انجام شد"}, status=status.HTTP_200_OK) with smtplib.SMTP_SSL(smtp_server, port, context=context) as server: server.login(sender_email, password) server.sendmail(sender_email, receiver_email, message.as_string()) elif response.status_code == 200 and response.text =='0': print(response, "else if error") return Response({"details": "تراکنش با موفقیت انجام نشد"}, status=status.HTTP_400_BAD_REQUEST) … -
"Could not parse some characters" in Crispy Form Django
I have a checkbox to filter the data in the template. While I have a field name which is having space in between words something like this: Dual Channel. I'm getting errors like this: Could not parse some characters: formChannel.Dual| Channel||as_crispy_field While when I have field names like single words then there is no problem for eg: Dual. but when I have words more than one, then it shows the above error. for eg: Dual Channel This is my template code: <form action="{% url 'main:other' %}" method="POST"> {% csrf_token %} {{ formChannel.Dual Channel|as_crispy_field }} </form> views.py if request.method == 'GET': formChannel = Form() elif request.method == 'POST': formChannel = Form(request.POST) if formChannel.is_valid(): channel_names = [] for channel_name in formChannel.cleaned_data: if formChannel.cleaned_data[channel_name] == True: channel_names.append(channel_name) if channel_names: channel = Channel.objects.filter(channel__in=channel_names) How to get rid out of this problem in Django crispy form -
Django form with queryset
I have a create view (Loan_assetCreateView(generic.CreateView)) where I save if an asset is going to be loaned and when it will be returened in a model called Loan_asset(models.Model). Then I have the asset in a diffrent model Asset(model.Model). I would like to once I have saved my data in my Loan_assetCreateView(generic.CreateView) that is set the value in Asset.is_loaned to True. Which it does with a signal, @receiver(post_save, I am trying to save the value. But the problem is with my form.py. In my forms.py I filter away assets that are not allowed to be loaned and assets that are loaned at the moment. That gives a problem when I try to edit/update it. Because the form does filter away it's own items. asset = forms.ModelChoiceField(required=False, queryset=Asset.objects.filter(Q(is_loaned=False) & Q(may_be_loaned=True)), label="Asset", widget=forms.Select(attrs={'class': 'form-control'})) forms.py class Loan_assetForm(forms.ModelForm): loaner_name = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner name'})) location = forms.ModelChoiceField(queryset=Locations.objects.all(), label="Asset loaned form", widget=forms.Select(attrs={'class': 'form-control'})) loaner_address = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaners address'})) loaner_telephone_number = forms.CharField(label="", max_length=100, widget=forms.TextInput( attrs={'class': 'form-control', 'placeholder': 'Loaner telephone number'})) loaner_email = forms.EmailField(label="", max_length=100, widget=forms.EmailInput( attrs={'class': 'form-control', 'placeholder': 'Loaners email'})) loaner_quicklink = forms.URLField(label="", max_length=100, required=False, widget=forms.URLInput( attrs={'class': 'form-control', 'placeholder': 'Quicklink'})) loaner_type = forms.ModelChoiceField(queryset=Loaner_type.objects.all(), label="Loaner type", widget=forms.Select(attrs={'class': 'form-control'})) …