Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to limit the image file size in image field in django admin panel (on client side)?
I am having few inline fields which have image field in them, what i'm trying to do is to determine the file size at the time of image selection, by selection I i would like to restrict the user before the request has been submitted. and I can do the file size check on the server using validators but in a few cases even before the validator can handle issue I got DATA_UPLOAD_MAX_MEMORY_SIZE exception, I do have enlarged the size , but still i could get that error that error of request body is exceeding max upload size. here is my code for the menu image class MenuImage(models.Model): """Salon Image Model""" class Meta: verbose_name = _("Menu Image") verbose_name_plural = _("Menu Images") salon = models.ForeignKey( Salon, on_delete=models.CASCADE, related_name='menu_images', null=True, blank=True) image = models.ImageField(upload_to='salon_images', help_text="Dimensions should in 175 x 100 px") def __str__(self): return self.salon.full_name def save(self, *args, **kwargs): compressed_image = ImageResizing.custom_resizing_and_compress(self.image) self.image = compressed_image super().save(*args, **kwargs) and this is how I am using it as an inline field class SalonModelAdmin(DjangoObjectActions, admin.ModelAdmin): inlines = [OpeningHoursInline, GalleryInline,MenuImageInline, SalonBankDetailInline, SalonLegalDocumentInline, SalonContactInline] fields = ("full_name","contact_number","neighbourhood", "salon_location","explore","salon_service","home_services", "featured","categories","commission", "cover_image","transportation_cost", "home_service_order_limit","logo_image", "salon_description","preference","auto_booking", "trending", "disable",) list_display = ("salon", "featured", "home_services", "contact_number", "commission",) search_fields = ['full_name'] list_filter = ("featured", … -
Django: How do I assign a button to take info and save()
Is there a way for the button to do the following? : When user press the button it takes the user.username of the current user and automatically fill up a form of BookInstance from models.py and save it to the database. From models.py : class BookInstance(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) book = models.ForeignKey("Book", on_delete=models.RESTRICT, null=True) imprint = models.CharField(max_length=200, blank=True, null=True) due_back = models.DateField(blank=True, null=True) borrower = models.ForeignKey( User, on_delete=models.SET_NULL, blank=True, null=True) LOAN_STATUS = ( ('m', 'Maintenance'), ('o', 'On Loan'), ('a', 'Available'), ('r', 'Reserved') ) status = models.CharField( max_length=1, choices=LOAN_STATUS, blank=True, default='a') class Meta: ordering = ['due_back'] def __str__(self): return f'{self.id} - {self.book.title}' def get_absolute_url(self): return reverse("catalog:book_list") class Book(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey( 'Author', on_delete=models.SET_NULL, null=True) summary = models.TextField( max_length=500, help_text="Enter brief description") isbn = models.CharField('ISBN', max_length=13, unique=True) genre = models.ManyToManyField(Genre, help_text="Select genre") language = models.ForeignKey( "Language", on_delete=models.SET_NULL, null=True) def __str__(self): return self.title def get_absolute_url(self): return reverse("catalog:book_detail", kwargs={"pk": self.pk}) This is my from my views.py : def borrowBook(request, pk): context = { 'book_instance': BookInstance.objects.all() } success_url = reverse_lazy('catalog:index') if request.method == "POST": form = BorrowForm(request.POST or None) if form.is_valid(): book_instance.id = BookInstance.objects.get(pk=pk) book_instance.book = BookInstance.objects.get(book=book) book_instance.borrower = request.user book_instance.status = 'o' book_borrowed_count = BookInstance.objects.filter( owner=request.user).count() if book_borrowed_count < … -
Using S3 and Django project: Imported javascript modules are not including the "X-Amz" parameters thus getting 403
On the HTML page I'm including a script with: <script type="module" src="{% static 'home/js/country/country.detail.js' %}"></script> That script loads just fine and then imports other modules: // country.detail.js file import FooConverter from "./foo.converter.js"; import Alert from "/static/app/alert.messenger.js"; import MESSAGES from "/static/app/messages.txt.js"; When the browser makes the request to fetch those other modules from the S3 bucket I get a 403 - Forbidden status code, because the browser is not including the "X-Amz" parameters: This is the request when the browser is fetching the fee.converter.js script (this one load fine): https://bucketname.s3.us-east-2.amazonaws.com/static/home/js/country/country.detail.js?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=creds%2F20230207%2Fus-east-2%2Fs3%2Faws4_request&X-Amz-Date=20230207T145100Z&X-Amz-Expires=3600&X-Amz-SignedHeaders=host&X-Amz-Signature=a5364797888bb0b7ce5ead84c656734dbd8b3093af43cf4ddc34a5734c28d743 This is the request when fetching alert.messenger.js (the response is 403, because it's missing the X-Amz parameters): https://bucketname.s3.us-east-2.amazonaws.com/static/app/alert.messenger.js How can I solve this? django-storages==1.13.1 Django==3.2.6 This is the CORS configuration in the bucket: { "CORSRules": [ { "ID": "allow-auth", "AllowedHeaders": [ "Authorization" ], "AllowedMethods": [ "GET" ], "AllowedOrigins": [ "*" ], "MaxAgeSeconds": 3000 }, { "ID": "allow-GET-locahost", "AllowedHeaders": [ "*" ], "AllowedMethods": [ "HEAD", "GET" ], "AllowedOrigins": [ "http://localhost" ], "ExposeHeaders": [ "ETag", "x-amz-meta-custom-header" ] } ] } -
django pagination with search not working
MultiValueDictKeyError at /search/ 'search' Request Method: GET Request URL: http://127.0.0.1:8000/search/?page=2 Django Version: 4.1.5 Exception Type: MultiValueDictKeyError Exception Value: 'search' Exception Location: C:\Python311\Lib\site-packages\django\utils\datastructures.py, line 86, in getitem Raised during: blogs.views.search Python Executable: C:\Python311\python.exe Python Version: 3.11.0 views.py def search(request): search = request.POST["search"] blog_search = Blog.objects.filter(Q(title__icontains=search) | Q(description__icontains=search)) paginator = Paginator(blog_search, 5) page_number = request.GET.get('page') blogs = paginator.get_page(page_number) return render(request,"frontend/searchblogs.html",{"blogs":blogs}) <div class="container"> <nav class="navbar navbar-light bg-light justify-content-end"> <form class="form-inline" method="post" action="{%url 'search' %}"> {% csrf_token %} <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search" name="search" id="search" > <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </nav> <h4 class="mt-4"></h4> {% for blog in blogs %} <div class="card mb-3" > <div class="row no-gutters"> <div class="col-md-4"> <img src="{{blog.cover_img.url}}" alt="..." class="bd-placeholder-img card-img-top img-fluid"> </div> <div class="col-md-8"> <div class="card-body"> <h4 class="card-title text-truncate">{{blog.title}}</h4> <p class="card-text text-truncate">{{blog.description}}</p> <div class="d-flex justify-content-between align-items-center"> <p class="text-muted">{{blog.date.date}}</p> <p class="text-muted"><i class="fa fa-eye pl-2"></i> {{blog.view}}</p> </div> </div> </div> </div> <a href="{%url 'blogdetail' blog.id %}" class=" stretched-link "></a> </div> {% endfor %} <nav aria-label="Page navigation example"> <ul class="pagination justify-content-end"> {% if blogs.has_previous %} <li class="page-item"> <a class="page-link" href="?page={{ blogs.previous_page_number }}">Previous</a> </li> {% else %} <li class="page-item disabled"> <a class="page-link" href="#" tabindex="-1" aria-disabled="True">Previous</a> </li> {% endif %} {% if blogs.number|add:'-4' > 1 %} <li class="page-item"><a class="page-link" href="?page={{ blogs.number|add:'-5' }}">&hellip;</a></li> {% … -
Django OTP authenticate user without password
I want to send a link to my users and when they press it, it asks for an OTP sent to the same email address. I would like to allow users with an email to login with OTP. To manually authenitcate django seems to require a Password to be passed. The user doesn't have a password I want them to login with the OTP sent to the email. What would be the best way to go about this? -
Multiple Dependent Dropdown in Django
I Need two pair dependent dropdown Field name: Country Field name: State note - Field name: Country and Field name: state should be dependent dropdown Field name: Product(Vegitable,Fruit) Field name: name of product note - Field name: Product(Vegitable,Fruit) and name of product should be dependent dropdown if I select Vegetable then Cabadge,Patato has to reflect and i select Fruit then Apple, Orange has to reflect 5. Field name : Status Category are Testing1,Testing2,Testing3 6. DateTime : mm-dd-yyyy hh:mm:ss Request please create small crud -
RuntimeError at /signup: Change your form to point to 127.0.0.1:8000/signup/ , or set APPEND_SLASH=False in your Django settings
RuntimeError at /signup You called this URL via POST, but the URL doesn't end in a slash and you have APPEND_SLASH set. Django can't redirect to the slash URL while maintaining POST data. Change your form to point to 127.0.0.1:8000/signup/ (note the trailing slash), or set APPEND_SLASH=False in your Django settings. I got this problem while using forms. Please help I have used bootstrap for styling <form action="/signup/" method = "post" > {% csrf_token %} <div class="input-group mb-3"> <span class="input-group-text" id="basic-addon1">@</span> <input type="text" class="form-control" placeholder="Username" name = "username" aria-label="Username" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Firstname" name="fname" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="text" class="form-control" placeholder="Lastname" name="lname" aria-describedby="basic-addon1"> </div> <div class="input-group mb-3"> <input type="email" class="form-control" placeholder="Recipient's email" name="email" aria-describedby="basic-addon2"> <span class="input-group-text" id="basic-addon2">@gmail.com</span> </div> <div class="input-group mb-3"> <input type="password" placeholder="password" name = "password" class="form-control"> </div> <div class="input-group mb-3"> <input type="password" placeholder="confirm password" name = "con_password" class="form-control"> </div> <div class="input-group mb-3"> <button type="submit" class="btn btn-primary">Signup</buttpn> </div> </form> </div> Views.py def signup(request): if (request.method == "POST"): username = request.POST.get("username") fname = request.POST.get("fname") lname = request.POST.get("lname") email = request.POST.get("email") password = request.POST.get("password") con_password = request.POST.get("con_password") User.objects.create_user(username=username, first_name=fname, last_name=lname, email=email, password=password) User.save() messages.success(request, "Account created successfully") return redirect("login") Should Redirect to login Page -
how to validation fields for TabularInline in django admin?
I create a BaseInlineFormSet like this: class `enter code here`ProductPictureRequiredFormSet(forms.models.BaseInlineFormSet): def clean(self): if self.cleaned_data["image"] == None: raise ValidationError("error") return self.cleaned_data["image"] and use this formset in my TabularInline class: class ProductPictureAdminInline(SortableTabularInline): formset = ProductPictureRequiredFormSet fields = ("title", "image", "is_default", "order", "created_by", "created_at", "updated_at") readonly_fields = ("created_by", "created_at", "updated_at") model = ProductPicture extra = 3 but i got this error: -
How to convert export Django QuerySet to one dictonary?
How to convert export Django QuerySet to one dictonary? I want to insert Django QuerySet as data_source into DataTable for Bokeh queryset = Model.objects.all() qs = queryset.values() qs = dict(qs) header = [field.verbose_name for field in Model._meta.get_fields()] columns = [TableColumn(field=col, title=col) for col in header] source = ColumnDataSource(qs) data_table = DataTable(source=source, columns=columns) script, div = components(data_table) qs = dict(qs) ^^^^^^^^ ValueError: dictionary update sequence element #0 has length 11; 2 is required -
Django (v4) request.META['REMOTE_ADDR'] not working anymore?
I had been using for years (Django 1.9 & Python 2.7) request.META dictionary and ['REMOTE_ADDR'] header to get client's IP address. I have recently moved to Django 4.1.5 and found out that my code is not able anymore to get client's IP address, so I had to use: x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip = x_forwarded_for.split(',')[0] else: ip = request.META.get('REMOTE_ADDR') return ip which works fine. I've tested my old code in development mode and tried to log request.META.get('REMOTE_ADDR'). The code will log IP only if the IP address is localhost (127.0.0.1). With any other IP address, REMOTE_ADDR header stays blank. I'm just curious, could someone tell me why this is happening? -
Greater than for INET IP address field in PostgreSQL Version > 9
So I have wrote my own lookups for PostgreSQL INET field in my DRF App as Django does not natively support those PostgreSQL specific fields. I use my own IP field in my objects to support my own lookups. All my lookup work find, except for those two: class HostGreaterOrEqual(Lookup): """ Lookup to check if an IP address is greater than or equal. Used for net ranges""" lookup_name = "host_greater_or_equal" def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return "%s >= %s" % (lhs, rhs), params class HostLessOrEqual(Lookup): """ Lookup to check if an IP address is less than or equal. Used for net ranges""" lookup_name = "host_less_or_equal" def as_sql(self, qn, connection): lhs, lhs_params = self.process_lhs(qn, connection) rhs, rhs_params = self.process_rhs(qn, connection) params = lhs_params + rhs_params return "%s <= %s" % (lhs, rhs), params In my models I have a address and address_end field to store IP Ranges. I wanted to use those lookups above to make the proper queries like this: items = queryset.filter( Q(address__host_greater_or_equal=value) & Q(address_end__host_less_or_equal=value) ) In the documentation for PostgreSQL Version 9 I can see the operators for "is lass or equal" and "is … -
Having trouble with pyodbc on django
I am working on django project. And testing Sql Server database. I am using korean linux hosting service gabia. So I don't have any root access. Even this hosting company blocked yum and rpm. Traceback (most recent call last): File "<stdin>", line 1, in <module> ImportError: libodbc.so.2: cannot open shared object file: No such file or directory I am keep having this kind of trouble when I import pyodbc. But I can fully use pymssql module. I have no idea what is wrong with this linux... This is when I connect django to mssql database with mssql-django package. Traceback (most recent call last): File "/web/.local/lib/python3.9/site-packages/mssql/base.py", line 16, in <module> import pyodbc as Database ImportError: libodbc.so.2: cannot open shared object file: No such file or directory During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.9/wsgiref/handlers.py", line 137, in run self.result = application(self.environ, self.start_response) File "/web/.local/lib/python3.9/site-packages/django/core/handlers/wsgi.py", line 130, in __call__ signals.request_started.send(sender=self.__class__, environ=environ) File "/web/.local/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 176, in send return [ File "/web/.local/lib/python3.9/site-packages/django/dispatch/dispatcher.py", line 177, in <listcomp> (receiver, receiver(signal=self, sender=sender, **named)) File "/web/.local/lib/python3.9/site-packages/django/db/__init__.py", line 46, in reset_queries for conn in connections.all(): File "/web/.local/lib/python3.9/site-packages/django/utils/connection.py", line 76, in all return [self[alias] for alias in self] File "/web/.local/lib/python3.9/site-packages/django/utils/connection.py", line … -
display an image on my pdf generate with render_to_pdf
I would like to display an image on my pdf that I generated from information views.py class GeneratePdf(View): def get(self, request, *args, **kwargs): data={'name':'toto','age':122,'service':'smapa'} pdf = render_to_pdf('cart/commande.html',data) return HttpResponse(pdf, content_type='application/pdf') utils.py from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from xhtml2pdf import pisa 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 result.getvalue() return None commande.html {% load static %} "" <body> <div class='wrapper'> <div class='header'> <p class='title'>Invoice # </p> <img src="{% static 'images/tof.png' %}" style="width:100px;height: 100px;"> </div> <div> <div class='details'> name: {{name}}<br/> age: {{age}} <br/> service: {{service}} <hr class='hrItem' /> </div> </div> </body> "" I cannot display the image, at the level of the pdf document it is mentioned at the level of the execution console, Need a valid file name -
"LoadMore" button on "Category product list" does not sort products by category
I did "Load More" button for "Product list" with tutorial and trying do like this on "Category product list", but it doest work normal. My files: Views.py def product_list(request): total_data = Product.objects.count() data = Product.objects.all().order_by('-id')[:1] cats = Product.objects.distinct().values('category__title', 'category__id') return render(request, 'product_list.html', { 'data': data, 'cats': cats, 'total_data': total_data, }) def category_product_list(request, cat_id): category = Category.objects.get(id=cat_id) total_data = Product.objects.filter(category=category).count() data = Product.objects.filter(category=category).order_by('-id')[:1] return render(request, 'category_product_list.html', {'data': data, 'total_data': total_data}) def load_more_data(request): offset = int(request.GET['offset']) limit = int(request.GET['limit']) data = Product.objects.all().order_by('-id')[offset:offset+limit] t = render_to_string('ajax/product-list.html', {'data': data}) return JsonResponse({'data': t}) def load_more_dataCat(request): offset = int(request.GET['offset']) limit = int(request.GET['limit']) data = Product.objects.filter(category=True).order_by('-id')[offset:offset+limit] t = render_to_string('ajax/category_product_list.html', {'data': data}) return JsonResponse({'data': t}) custom.js $(document).ready(function(){ $("#loadMore").on('click', function(){ var _currentProducts = $(".product-box").length; var _limit = $(this).attr('data-limit'); var _total = $(this).attr('data-total'); console.log(_total) // Start Ajax $.ajax({ url:'/load-more-data', data:{ limit: _limit, offset: _currentProducts }, dataType:'json', beforeSend:function(){ $("#loadMore").attr('disabled',true); $(".load-more-icon").addClass('fa-spin'); }, success:function(res){ $("#filteredProducts").append(res.data); $("#loadMore").attr('disabled',false); $(".load-more-icon").removeClass('fa-spin'); var _totalShowing = $(".product-box").length; if(_totalShowing==_total){ $("#loadMore").remove(); } } }); // End }); }); $(document).ready(function() { $("#loadMoreCat").on('click', function () { var _currentProducts = $(".product-box").length; var _limit = $(this).attr('data-limit'); var _total = $(this).attr('data-total'); console.log(_total) // Start Ajax $.ajax({ url:'/load-more-dataCat', data:{ limit: _limit, offset: _currentProducts }, dataType:'json', beforeSend:function(){ $("#loadMoreCat").attr('disabled',true); $(".load-more-icon").addClass('fa-spin'); }, success:function(res){ $("#categoryProducts").append(res.data); $("#loadMoreCat").attr('disabled',false); $(".load-more-icon").removeClass('fa-spin'); var _totalShowing = $(".product-box").length; … -
why first parameter is send as id to views in django
while writing urls if i write interchange position of int:post_id with share it is not working. urls.py of application urlpatterns = [ #path("",views.list_view,name="post_list"), path("",views.PostListView.as_view(),name="post_list"), path("<str:post>/<int:id>/",views.post_detail,name="post_details"), path('<int:post_id>/share/',views.post_share,name="post_share"), #if i write a path like this path('share/<int:post_id>/',views.post_share,name="post_share"), #it is not working. ] views.py (only part where i have problem) def post_share(request,post_id): #post=get_object_or_404(Post,status=Post.Status.PUBLISHED,id=post_id) #post=get_object_or_404(Post,status=Post.Status.PUBLISHED,id=id) post = get_object_or_404(Post,id=post_id, status=Post.Status.PUBLISHED) #post=Post.objects.get(id=3) sent=False if request.method=='POST': form=EmailPostForm(request.POST) if form.is_valid(): cd=form.cleaned_data print(cd) post_url=request.build_absolute_uri(post.get_absolute_url) subject=f"{cd['name']} recommends {post.title}" message=f'Here is the link to read {post_url}' send_mail(subject,message,'abcxyzalpha42@gmail.com',[cd['to']]) sent=True else: form=EmailPostForm() context={'form':form,'post':post,'sent':sent} return render(request,'app1/post/post_share.html',context) -
Get all records with the same Field1 and different Field2 Django ORM
Good afternoon! I have a model of the following format class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='orders') address = models.CharField(max_length=255, null=True, blank=True) .... I need to get all the records with the same address, but with different user. Tell me, please, how can I fulfill this request? A request in this format outputs an error orders = Order.objects\ .filter(...)\ .distinct('address', 'user')\ .annotate(Count('address')\ .filter(address__count_gt=1) NotImplementedError: annotate() + distinct(fields) is not implemented. And if so, then count counts incorrectly and I lose data because of values (I need not to lose the order object) orders = Order.objects\ .filter(...)\ .values('address', 'user')\ .distinct()\ .annotate(Count('address')\ .filter(address__count_gt=1) -
an Inline class isnt working in django admin
I created a ProductAttributes model that have a ForeignKey from Product model now i'm trying to create an admin panel for adding product using django admin i'm adding ProductAttributes to Product admin with TabularInline but its not working this the models and admin classes #models class Product(models.Model): title = models.CharField(max_length=255) slug = models.SlugField() description = models.TextField(null=True, blank=True) introduction = models.TextField(null=True, blank=True) unit_price = models.DecimalField( max_digits=12, decimal_places=2, validators=[MinValueValidator(1)]) inventory = models.IntegerField(validators=[MinValueValidator(0)]) last_update = models.DateTimeField(auto_now=True) collection = models.ForeignKey(Collection, on_delete=models.PROTECT, related_name='products') promotions = models.ManyToManyField(Promotion, blank=True) def __str__(self) -> str: return self.title class Meta: ordering = ['title'] class ProductAttributes(models.Model): Product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="attributes") attribute = models.CharField(max_length=255) #admin class ProductAttributesInline(admin.TabularInline): model = models.ProductAttributes @admin.register(models.Product) class ProductAdmin(admin.ModelAdmin): autocomplete_fields = ['collection'] prepopulated_fields = { 'slug': ['title'] } actions = ['clear_inventory'] inlines = [ProductAttributesInline] list_display = ['title', 'unit_price', 'inventory_status', 'collection_title'] list_editable = ['unit_price'] list_filter = ['collection', 'last_update', InventoryFilter] list_per_page = 10 list_select_related = ['collection'] search_fields = ['title'] def collection_title(self, product): return product.collection.title @admin.display(ordering='inventory') def inventory_status(self, product): if product.inventory < 10: return 'Low' return 'OK' @admin.action(description='Clear inventory') def clear_inventory(self, request, queryset): updated_count = queryset.update(inventory=0) self.message_user( request, f'{updated_count} products were successfully updated.', messages.ERROR ) class Media: css = { 'all': ['store/style.css'] } the ProductAttributes isnt shown in Product admin … -
How can I integrate grid.js plugin in Django templates?
I'm trying to integrate the gridjs plugin into the django templates and I would like to display html content in cells to format the status of a product. I would also like to add svg images in certain cells. Can anyone help me with an implementation? The plugin documentation refers to React, Angular, etc implementations. I use gridjs with jquery. <script> $("div#pigeon-table").Grid({ search: true, pagination: true, sort: true, columns: [ { name: "{% translate "Gender" %}", formatter: "set the html formatter" }, "{% translate "Ring details" %}", "{% translate "Color" %}", "{% translate "Section" %}", "{% translate "Strain" %}", "{% translate "Sire" %}", "{% translate "Dam" %}", "{% translate "Status" %}"], data: [ {% for p in pigeons %} [ "svg image here", "{{ p.ring_serial }}", "{% translate p.color.color %}", "{{ p.get_section_display }}", "{{ p.strain }}", "{{ p.sire }}", "{{ p.dam }}", "{{ p.status.color }}", "{% translate p.status.status %}" ], {% endfor %} ] }); </script> -
Django keyword reject argument 'disabled'
I try make 2 fields in fieldset possible to edit (others should be only visible), but I have problem with parameters: my code: def get_fieldsets(self, request, obj=None): fieldsets = self.fieldsets if request.user.groups.filter(name='copywriter').exists(): editable_fields = ['author', 'month'] readonly_fields = [field for field in self.fieldsets[0][1]['fields'] if field not in editable_fields] fieldsets = [(None, {'fields': editable_fields})] + [(None, {'fields': readonly_fields, 'disabled': True})] return fieldsets But anytime when I go to record view, I see "Fieldset.init() got an unexpected keyword argument 'disabled'" error. How can I fix it? I don't know where exactly is error, I'm using keyword from documentation, but it doesn't work. -
Create multiple choice field dynamically
My purpose is to create a django form to select devices filtered by country and club fields. My form is this: class MyForm(Form): country = ChoiceField(choices=some_choices, initial=None) club = CharField(widget=Select()) expiration_date = DateField() sales_info = ChoiceField(choices=SALES_TYPES, initial=None) devices = MultipleChoiceField(widget=CheckboxSelectMultiple(choices=[])) def clean_devices(self): devices = self.cleaned_data.get("devices") if not devices: raise ValidationError("At least one device must be selected.") return devices def save(self): ... views.py class MyFormView(LoginRequiredMixin, FormView): template_name = "store/my_template.html" form_class = MyFormView def get_success_url(self): return reverse('init_device') def form_valid(self, form): init_device = form.save() if init_device: return super().form_valid(form) return super().form_invalid(form) def form_invalid(self, form): logger.error(form.errors) my_template.html <form action="{% url 'init_device' %}" method="post"> {% csrf_token %} ... <select id="id_devices" name="devices" multiple> I populate select field via javascript in this way: let device_select = document.getElementById("id_devices"); serialIds.forEach(serialId => { let option = document.createElement("option"); option.text = serialId; option.value = serialId; device_select.add(option); }); I obtained filtered devices form db using a websocket by now I can't pass them to the form because this error raises: ValueError: The view path.view didn't return an HttpResponse object. It returned None instead. Then I print form.errors and this is showed <ul class="errorlist"><li>devices<ul class="errorlist"><li>Select a valid choice. device_attriubte is not one of the available choices.</li></ul></li></ul> Can anyone help me? Thank you in advance! -
How can I use python function in html? [closed]
I am a beginner in django and I am developing django code. The previous programmer linked html files to Django with js instead of using template tag. I want to use Python function in my template, is there a solution? -
Creating a custom serializer in django
I am facing a problem, because I have to create a custom serializer to fulfill my needs. These are my models: class PublicID(models.Model): TYPE_FIELDS = ( ('M', 'monkey'), ('A', 'alien'), ('P', 'person'), ) public_id = models.CharField(unique=True, max_length=48, editable=False) obj_type = models.CharField(choices=TYPE_FIELDS, max_length=1) class Request(models.Model): source = models.ForeignKey(PublicID, related_name='source_request_set', on_delete=models.CASCADE) dest = models.ForeignKey(PublicID, related_name='dest_request_set', on_delete=models.CASCADE) class Monkey(models.Model): nickname = models.CharField(max_length=255) public_id = models.OneToOneField(PublicID, related_name='monkey', blank=True, on_delete=models.CASCADE) class Alien(models.Model): alias = models.CharField(max_length=255) public_id = models.OneToOneField(PublicID, related_name='alien', blank=True, on_delete=models.CASCADE) class Person(models.Model): first_name = models.CharField(max_length=255) public_id = models.OneToOneField(PublicID, related_name='person', blank=True, on_delete=models.CASCADE) Note that all types of obj_types can send Request to every type of obj_types. e.g. we can have a Monkey which sends a request to an Alien through their unique PublicIDs. My Serializer looks like this: class RequestSerializer(serializers.ModelSerializer): class Meta: model = Request exclude = ['id'] def validate_source(self, value): obj_type = value.get('obj_type') if obj_type is None: raise serializers.ValidationError('`obj_type` field is required.') # other checks return value def validate_dest(self, value): obj_type = value.get('obj_type') if obj_type is None: raise serializers.ValidationError('`obj_type` field is required.') # other checks return value def run_validation(self, attrs): source = attrs.get('source') dest = attrs.get('dest') if source is None or dest is None: raise serializers.ValidationError('`source` and `dest` fields are ' 'required.') self.validate_source(source) self.validate_dest(dest) … -
Hey. I have an error when try to install mysqlclient to my Django project on Mac
Collecting mysqlclient Using cached mysqlclient-2.1.1.tar.gz (88 kB) Preparing metadata (setup.py) ... done Building wheels for collected packages: mysqlclient Building wheel for mysqlclient (setup.py) ... error error: subprocess-exited-with-error × python setup.py bdist_wheel did not run successfully. │ exit code: 1 ╰─> [43 lines of output] mysql_config --version ['8.0.32'] mysql_config --libs ['-L/usr/local/Cellar/mysql/8.0.32/lib', '-lmysqlclient', '-lz', '-L/usr/local/lib', '-lzstd', '-L/usr/local/opt/openssl@1.1/lib', '-lssl', '-lcrypto', '-lresolv'] mysql_config --cflags ['-I/usr/local/Cellar/mysql/8.0.32/include/mysql'] ext_options: library_dirs: ['/usr/local/Cellar/mysql/8.0.32/lib', '/usr/local/lib', '/usr/local/opt/openssl@1.1/lib'] libraries: ['mysqlclient', 'resolv'] extra_compile_args: ['-std=c99'] extra_link_args: [] include_dirs: ['/usr/local/Cellar/mysql/8.0.32/include/mysql'] extra_objects: [] define_macros: [('version_info', "(2,1,1,'final',0)"), ('version', '2.1.1')] running bdist_wheel running build running build_py creating build creating build/lib.macosx-10.9-universal2-cpython-311 creating build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/init.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/_exceptions.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/connections.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/converters.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/cursors.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/release.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb copying MySQLdb/times.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb creating build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/init.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/CLIENT.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/CR.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/ER.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/FIELD_TYPE.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants copying MySQLdb/constants/FLAG.py -> build/lib.macosx-10.9-universal2-cpython-311/MySQLdb/constants warning: build_py: byte-compiling is disabled, skipping. running build_ext building 'MySQLdb._mysql' extension creating build/temp.macosx-10.9-universal2-cpython-311 creating build/temp.macosx-10.9-universal2-cpython-311/MySQLdb clang -Wsign-compare -Wunreachable-code -fno-common -dynamic -DNDEBUG -g -fwrapv -O3 -Wall -arch arm64 -arch x86_64 -g -Dversion_info=(2,1,1,'final',0) -D__version__=2.1.1 -I/usr/local/Cellar/mysql/8.0.32/include/mysql -I/Users/pro/.local/share/virtualenvs/storefront-qb_mvtC8/include -I/Library/Frameworks/Python.framework/Versions/3.11/include/python3.11 -c MySQLdb/_mysql.c -o build/temp.macosx-10.9-universal2-cpython-311/MySQLdb/_mysql.o -std=c99 xcrun: error: invalid active developer path (/Library/Developer/CommandLineTools), missing xcrun at: /Library/Developer/CommandLineTools/usr/bin/xcrun error: … -
Mutiple Forms Saved using one unique ID
I'm trying to save mutiple forms for spe_form using a unique ID for gen_format the same time using the template below by clicking on save button. Could you please help me with that? The code works only for one save for only form of spe_form but not for many def preps(request, prep=None): if prep_General: info = Mprep.objects.get(id=prep) else: info = Mprep() # Handle form submissions if request.method == 'POST': # Instantiate the forms with submitted data gen_form = MGForm(request.POST, instance=info) spe_form = MSForm(request.POST, prefix='preps') if gen_form.is_valid() and spe_form.is_valid(): gen_form.save() preps = spe_form.save(commit=False) preps.prep = info preps.save() messages.success(request, 'Information saved successfully') return redirect('preps_view', prep=info.id) else: messages.error(request, 'Error in saving information') else: gen_form = MGForm(instance=info) spe_form = MSForm(prefix='preps') context = {'gen_form': gen_form, 'spe_form': spe_form} return render(request, 'base.html', context) <div class="container mt-5"> <h1>Measurements Prep</h1> <form method="post"> {% csrf_token %} <div class="form-row"> <div class="form-group col-4"> {{ gen_form.project|as_crispy_field }} </div> <div class="form-group col-4"> {{ gen_form.cell|as_crispy_field }} </div> <div class="form-group col-4"> {{ gen_form.sample|as_crispy_field }} </div> </div> <br> <table id="myTable" class="table" data-toggle="table" data-mobile-responsive="true" data-pagination="true" data-height="460"> <tbody> <tr> <th>{{ spe_form_set.name|as_crispy_field }}</th> <th>{{ spe_form_set.value|as_crispy_field }}</th> <th>{{ spe_form_set.unit|as_crispy_field }}</th> </tr> </tbody> <button id="add-row-button" class="btn btn-primary mt-4">Add Row</button> </table> <input type="submit" class="btn btn-primary mt-4" value="Save"> </form> </div> <script> document.getElementById("add-row-button").addEventListener("click", function () … -
how to show vue js variables in django
I've this simple code in a **django ** in test.html: <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script> <div id="app">the message:{{ message }}</div> <script> const { createApp } = Vue createApp({ data() { return { message: 'Hello Vue!' } } }).mount('#app') </script> in urls.py: urlpatterns = [ path('test', dashboard_views.test,name='test'), in views.py def test(request): return render(request,"test.html") output on screen: the message: how can I fix this to show "Hello Vue!"