Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django re_path url not matching values supplied in template
I am trying to match URLs that match var1/integer of any length/var2/single integer between 1 and 5 (inclusive). I have the expression (regex101) below that I know I am trying to convert into URL pattern in Django (var1)\/\d{1,}\/(var2)\/[1-5]$ I am trying to generate URL pattern in urls.py like this: urlpatterns = [ path('admin/', admin.site.urls), re_path(r'(var1)\/<var1_id>\d{1,}\/(var2_id)\/<var2_id>[1-5]', edit, name='url_name'), ] The href value I'm trying to build with it, from template <a href="{% url 'url_name' var1_id=var1.id var2_id=1 %}"> The error I'm getting is Reverse for 'url_name' with keyword arguments '{'var1_id': 1, 'var2_id': 1}' not found. 1 pattern(s) tried: ['(var1)\/<var1_id>\d{1,}\/(var2)\/<var2_id>[1-5]'] How can I make the re work for var1/1/var2/1, for example? -
Getting error on adding class in admin.site.register function
i am getting this error when i try to add ProductoAdmin class in admin.site.register function. from django.contrib import admin from .models import Marca, Producto # Register your models here. class ProductoAdmin(admin.ModelAdmin): list_display = ('nombre', 'precio', 'nuevo', 'marca') list_editable = ["precio"] search_fields = ["nombre"] admin.site.register(Marca) admin.site.register(Producto, ProductoAdmin) Error <class 'app.admin.ProductoAdmin'>: (admin.E108) The value of 'list_display[2]' refers to 'nuevo', which is not a callable, an attribute of 'ProductoAdmin', or an attribute or method on 'app.Producto'. -
malti rows in table
hi i want to build table have about 100 empty rows and after created edit it and must 100 rows appear on template how can do it for example i have TAG BLOC in my BAPX telecom and i want to store the data in table the TAG BLOC have 100 empty lines whoever some times line one is busy and line tow is empty and line four is busy so i want to store all line busy and in future can store empty linesenter image description here i want table like this -
Why do I keep getting Class ModelSerializer missing "Meta" attribute?
whenever I try to access the view for my registration serializer I keep getting that I'm missing the Meta attribute even though it's there. I tried making some changes to the code but it doesn't seem to work so it's clearly something I'm missing. Why is this happening? This is the serializer: class UserRegistrationSerializer(serializers.ModelSerializer): username = serializers.CharField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) email = serializers.ModelSerializer( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( required=True, label="Password", style={'input_type': 'password'} ) password_2 = serializers.CharField( required=True, label="Confirm Password", style={'input_type': 'password'} ) class Meta(object): model = User fields = ['username', 'email', 'password', 'password_2',] def validate_password(self, value): if len(value) < 8: raise serializers.ValidationError( "Password should be at least 8 characters long.") return value def validate_password_2(self, value): data = self.get_initial() password = data.get('password') if password != value: raise serializers.ValidationError("Passwords doesn't match.") return value def validate_username(self, value): if User.objects.filter(username=value).exists(): raise serializers.ValidationError("Username already exists.") return value def create(self, validated_data): user_data = { 'username': validated_data.get('username'), 'email' : validated_data.get('email'), 'password': validated_data.get('password'), } user = User.objects.create_user( data=user_data, site=get_current_site(self.context['request']) ) return validated_data -
Why do I keep getting a NoReverse Error in Django 3.2
I know this question has already been asked but none of the solutions are specific to the version of Django that I am using, which is 3.2. So I am following the Django tutorial and I am getting this error. I am using the generic views in Django just like the tutorial did. Before using generic views everything was working. Do I have to hardcode my views or did I implement the generic views wrong? Internal Server Error: /polls/ Traceback (most recent call last): File "C:\Users\miche\tutorial-env\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\miche\tutorial-env\lib\site-packages\django\core\handlers\base.py", line 204, in _get_response response = response.render() File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\response.py", line 83, in rendered_content return template.render(context, self._request) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\defaulttags.py", line 312, in render return nodelist.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\defaulttags.py", line 211, in render nodelist.append(node.render_annotated(context)) File "C:\Users\miche\tutorial-env\lib\site-packages\django\template\base.py", line 905, in render_annotated return … -
Can't execute my functions out of the fetch function - JavaScript
it's my first JavaScript snippet. I run into the following problem. I'm trying to load serialized with Django Rest Framework data and then render the list of questions and the pagination bar. I also have likeQuestion, PaginationListener and SortingListener functions. In the snippet below I execute likeQuestion, PaginationListener and SortingListener functions within fetch function. It works but since it turns out to be recursive it results in multiple http-requests doubling with every click (actually only SortingListener function behaves this way, PaginationListener - surprisingly don't). I also tried to execute all the three functions out of the fetch function. It doesn't work: when I try to get the elements the html collection is zero length. I tried it with window.addEventListener('DOMContentLoaded', (e) => {}). Still doesn't work. Outside the fetch function it works only with setTimeout. But in this case the PaginationListener works only for the first click. And timeout seems to be not a very good decision. How should I change my code to make it work smoothly? const url = document.getElementById('question-list').dataset.url getQuestionList(url) // Ask.index page loading function getQuestionList(url) { const questionList = document.getElementById('question-list') fetch(url).then(response => response.json()).then(json => { // Questions List loading questionList.innerHTML = '' for(const question of json.results){ date … -
DJANGO for loop to show product images from thumbnails
I have a product detail page with images of the product. The number of images is not fixed, and the images are uploaded using a multi-upload function. This is all working correctly. I am now having problems getting the images to show and be selectable by the user from the thumbnail in the main produce viewer. The images show, but the user can not click on an image thumbnail to show that image in the viewer. The code works if the image locations are hardcoded and for that reason I have not included the javascript that changes the images. Is there a simple pythonic way of doing this in the view or the template. Template.html <section class="shop-banner-area pt-100 pb-70"> <div class="container"> <div class="row"> <div class="col-xl-6 col-lg-6"> <div class="shop-thumb-tab"> <ul class="nav" id="myTab2" role="tablist"> {% for obj in rx %} <li class="nav-item"> <a class="nav-link active" id="home-tab" data-toggle="tab" href="#home" role="tab" aria-selected="false"><img src="{{obj.Rx_copy.url}}" alt=""> </a> </li> <li class="nav-item"> <a class="nav-link" id="profile-tab" data-toggle="tab" href="#profile" role="tab" aria-selected="false"><img src="{{obj.Rx_Copy.url}}" alt=""></a> </li> {% endfor %} <li class="nav-item"> <a class="nav-link" id="profile-tab2" data-toggle="tab" href="#profile1" role="tab" aria-selected="false"><img src="assets/img/products/pr-33.png" alt=""></a> </li> </ul> </div> <div class="product-details-img mb-30"> <div class="tab-content" id="myTabContent2"> {% for obj in rx %} <div class="tab-pane fade show active" id="home" role="tabpanel">[enter … -
Content of for loop not showing in email
I'm using a HTML template for sending emails. Email is delivering fine except it missed out a part containing for loop which I needed to iterate a nested data from the database. {% for item in data.cart.all %} {{ forloop.counter }} <table class="tg"> <tbody> <tr class="stdfont"> <th class="tg-0lax leftc"> {{ item.item_quantity }} x {{ item.item_name }} </th> <th class="tg-baqh rightc">£{{ item.item_price }}</th> </tr> </tbody> <tbody> <tr> <td class="tg-0lax1 stdfont3">{{ item.item_selection }}</td> <td class="tg-0lax"></td> </tr> </tbody> </table> {% endfor %} Views.py def send_email(request, subject,template,dbclass): subject = request.POST.get('subject', subject) message = request.POST.get('message', 'how are you') from_email = request.POST.get('from_email', 'email') if subject and message and from_email: data = dbclass html_message = render_to_string(template, {'data': data}) try: send_mail(subject, message, from_email, ['email'],html_message=msg_html,) except BadHeaderError: return HttpResponse('Invalid header found.') return HttpResponseRedirect('/contact/thanks/') else: return HttpResponse('Make sure all fields are entered and valid.') class CartView(viewsets.ModelViewSet): date_from = datetime.datetime.now() - datetime.timedelta(days=1) queryset = Cart.objects.filter( order_date_time__gte=date_from) serializer_class = CartSerializer lookup_field = 'custom_key' pagination_class = None def create(self, request, *args, **kwargs): response = super(CartView, self).create(request, *args, **kwargs) send_email(request,'Order Confirmed','email/invoice.html',Cart.objects.last()) # sending mail return response If I render the same info, for loop is showing fine there. def check_email(request): data = Cart.objects.last() context = {'data': data} return render(request, 'email/invoice.html', context) I'm not sure … -
How to create a custom template tag that passes in a dictionary of more than one object in django
I want to create a template tag that passes in a dictionary of objects models.py class Notification(models.Models): name = models.CharField() .......... template_tag.py created a template tag that gets all the objects that I want to display from django import template register = template.Library() @register.simple_tag def notifications(): context = {'notifications':Notification.objects.order_by('-date')[:4]} return context The later initiate a forloop that displays the objects {% load template_tag %} {% for obj in notifications %} <a href="">{{ obj.name }}</a> {% endfor %} Hope you get the idea..... -
Are there any updated and working Django in line editing packages?
And if not, is there an easy way to implement this? The editing would also save to the database as well. I've checked out https://djangopackages.org/ and none of them seem to be updated and working with Django 3.0+. -
Enum, Unsupported lookup 'eq' for CharField
I have piece of code, which worked fine with Python 3.9 and Django 1.11. I made an update to Python 3.9 and Django 3.2 and I'm getting the following error Traceback (most recent call last): File "D:\Code\Virtualenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\Code\Virtualenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\Code\octo\OctoServ\views.py", line 615, in temp sums = qsSchedules.filter(Employee=e).values('Date', 'Type').order_by('Date').annotate(sum=typefilter) File "D:\Code\Virtualenv\lib\site-packages\django\db\models\query.py", line 1091, in annotate return self._annotate(args, kwargs, select=True) File "D:\Code\Virtualenv\lib\site-packages\django\db\models\query.py", line 1130, in _annotate clone.query.add_annotation( File "D:\Code\Virtualenv\lib\site-packages\django\db\models\sql\query.py", line 1042, in add_annotation annotation = annotation.resolve_expression(self, allow_joins=True, reuse=None, File "D:\Code\Virtualenv\lib\site-packages\django\db\models\aggregates.py", line 48, in resolve_expression c.filter = c.filter and c.filter.resolve_expression(query, allow_joins, reuse, summarize) File "D:\Code\Virtualenv\lib\site-packages\django\db\models\query_utils.py", line 104, in resolve_expression clause, joins = query._add_q( File "D:\Code\Virtualenv\lib\site-packages\django\db\models\sql\query.py", line 1415, in _add_q child_clause, needed_inner = self.build_filter( File "D:\Code\Virtualenv\lib\site-packages\django\db\models\sql\query.py", line 1350, in build_filter condition = self.build_lookup(lookups, col, value) File "D:\Code\Virtualenv\lib\site-packages\django\db\models\sql\query.py", line 1190, in build_lookup lhs = self.try_transform(lhs, lookup_name) File "D:\Code\Virtualenv\lib\site-packages\django\db\models\sql\query.py", line 1229, in try_transform raise FieldError( django.core.exceptions.FieldError: Unsupported lookup 'eq' for CharField or join on the field not permitted. The error is caused by the line typefilter = Sum('Minutes', filter=(Q(Type__eq=scheduleChoice.G) | Q(Type__eq=scheduleChoice.D))) in views.py, which is as follows [...] emp = employee.objects.filter(Status=1) sDate = request.POST["sDate"] eDate = request.POST["eDate"] qsSchedules = … -
What is the best practice for updating Django models, Signals, @properties, Other?
At the moment I am re writing my eCommerce site. I have come up with 2 ways to update the cart subtotal when ever an item is added or removed I'm not sure which way is best Perhaps it doesn't even matter which lol any advice would be appreciated Model: from django.conf import settings from django.db import models from django.db.models.signals import pre_save, post_save, m2m_changed from products.models import Product User = settings.AUTH_USER_MODEL class CartItemManagerQuerySet(models.query.QuerySet): pass class CartItemManager(models.Manager): def get_queryset(self): return CartItemManagerQuerySet(self.model, using=self._db) class CartItem(models.Model): product = models.ForeignKey(Product, null=True, blank=True, on_delete=models.SET_NULL) quantity = models.IntegerField(default=0, null=True) price_of_item = models.FloatField(default=0.00) total = models.FloatField(default=0.00) objects = CartItemManager() def __str__(self): return str(self.product.title + ", total: £" + str(self.total)) def cart_item_pre_save_receiver(sender, instance, *args, **kwargs): instance.price_of_item = instance.product.price instance.total = instance.price_of_item * instance.quantity pre_save.connect(cart_item_pre_save_receiver, sender=CartItem) class Cart(models.Model): user = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL) cart_items = models.ManyToManyField(CartItem, blank=True) tax_percentage = models.FloatField(default=0.20) tax_total = models.FloatField(default=0.00) subtotal = models.FloatField(default=0.00) updated = models.DateTimeField(auto_now=True) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return str(str(self.user) + ": " + str(self.subtotal)) I could append the code below: @property def update_total(self): total = 0.0 for cart_items in self.cart_items.all(): total += cart_items.total self.tax_total = self.tax_percentage * total self.subtotal = self.tax_total + total self.save() Then I can simply do below: cart_obj.cart_items.add(cart_item_1) … -
Error type object 'Configuration' has no attribute 'environment' when using braintree, Django
I'm trying to learn Django with the book "Django 3 by example" written by Antiono Mele and I have a problem with configuration of sandbox enviroment while using braintree. In their page there is written: gateway = braintree.BraintreeGateway( braintree.Configuration( environment=braintree.Environment.Sandbox, merchant_id='**********', public_key='**********', private_key='**********' ) ) exactly the same as in the book. When I try to make payment Error type object 'Configuration' has no attribute 'environment'. I don't have any idea why there is an error. I check versions of applications used by me and they match with those in book (Pillow==7.0.0., Django==3.1.8, celery==4.4.2, braintree==3.59.0). Below I put code needed. payment/views.py import braintree from django.shortcuts import render, redirect, get_object_or_404 from orders.models import Order gateway = braintree.BraintreeGateway( braintree.Configuration( environment=braintree.Environment.Sandbox, merchant_id='**********', public_key='**********', private_key='**********' ) ) # Utworzenie egzemplarza bramki płatności Braintree. def payment_process(request): order_id = request.session.get('order_id') order = get_object_or_404(Order, id=order_id) if request.method == 'POST': # Pobranie tokena nonce. nonce = request.POST.get('payment_method_nonce', None) # Utworzenie i przesłanie transakcji. result = braintree.Transaction.sale({ 'amount': '{:.2f}'.format(order.get_total_cost()), 'payment_method_nonce': nonce, 'options': { 'submit_for_settlement': True } }) if result.is_success: # Oznaczenie zamówienia jako opłacone. order.paid = True # Zapisanie unikatowego identyfikatora transakcji. order.braintree_id = result.transaction.id order.save() return redirect('payment:done') else: return redirect('payment:canceled') else: # Wygenerowanie tokena. client_token = braintree.ClientToken.generate() return … -
Setting up VSCode to debug Vue in a Django app
I'm struggling to debug Vuejs code (with breakpoints) that is part of a django project. Django debugging works fine, but I can't wrap my head around how to setup the Vue parts. I've followed several recipes online, but they all assume a pure Vue app and/or a Vue app that is located at the project root. I've tried them all, but nothing I've tried even brings up a page in a browser to debug, nevermind triggering a breakpoint. The project is setup like this: . ├── django_app │ ├── * │ ├── migrations │ ├── static │ ├── templates │ ├── templatetags │ ├── tests │ └── views ├── staticfiles │ ├── assets │ ├── css │ ├── * │ ├── js │ └── vue │ ├── css │ └── js │ └── vue ├── node_modules ├── src │ ├── AppPage1 │ │ ├── AppPage1.vue │ │ └── main.js │ ├── AppPage2 │ │ ├── AppPage2.vue │ │ └── main.js ├── package.json └── vue.config.js launch.json { "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Chrome/Vue Debug", "url": "http://localhost:8000", "webRoot": "${workspaceFolder}", "sourceMaps": true, "sourceMapPathOverrides": { "webpack:/*": "${webRoot}/*", "/./*": "${webRoot}/*", "/src/*": "${webRoot}/*", "/*": "*", "/./~/*": "${webRoot}/node_modules/*" }, "preLaunchTask": "vuejs: start" … -
How to get a sum from a Django filter query
I have used the following query, and I am trying to get the Sum of 'fee' reg_total_fees =orders.aggregate(all_sum=Sum('par_payment__fee')) but I get this: {'all_sum': 1785} Do you know how I could just get the value? -
Random TextNode appearing in Django authentication templates
I am using custom templates with django.contrib.auth.urls and I've noticed that in the top left corner I have plain text appearing that isn't part of my template e.g. "Password Reset" on the password reset page, "Password Change" on the change password page etc. When I use my browser to inspect the element it simply appears as plain text in the page source. When I click the relevant line in the page source some properties appear in the side panel and it appears to be a "Text Node" with a value of the text that is shown in my template. The text only shows on change password and reset password related pages (including reset done etc). It doesn't show on the login page or any other page in the app. What is this and how do I get rid of it? I have used django.contrib.auth.urls with custom templates before and have not come across this before. Thanks -
How do i make reportlab works django on server?
I used reportlab 3.5.59 at django 3.1.3 in python 3.8 It uses io buffer and download that pdf. It is working in my localhost. but when i deployed it into server it wouldn't work... The code is : result = ['I','Have','a','Problem'] from reportlab.pdfgen import canvas import io buffer = io.BytesIO() file_name = f'{result[0][0:10]}.pdf' pdf = canvas.Canvas(buffer) pdf.setTitle(f'{file_name}') text =pdf.beginText(40,800) text.setFont('Courier',10) for line in result: text.textLine(line) pdf.drawText(text) pdf.showPage() pdf.save() buffer.seek(0) return FileResponse(buffer, as_attachment=True, filename=file_name) And shows "The server encountered an unexpected condition which prevented it from fulfilling the request." error messeege... please tell me whats wrong with it. -
Django 2 to 3 upgrade throws error: "on_delete must be callable"
In upgrading from Django 2 to 3.2, upon running my server, I suddenly get the following error: TypeError: on_delete must be callable. The model field in question is this one: game_played = models.ForeignKey(Game, "Game Played", help_text="Game Played", null=True, blank=False) As you can see, on_delete is not called on this field. Reverting back to Django 2 fixes this issue in that it no longer returns the error. I have tried to add on_delete to the field, which results in this error: TypeError: __init__() got multiple values for argument 'on_delete' I have reviewed the Django 3 docs and cannot find anything related to changes to on_delete that would affect this. All I can find regarding on_delete issues are that sometimes people put models.CASCADE in quotes versus making it callable but that is not the issue here. How would I fix this issue? -
JavaScript can't find element created by Django form
I'am developing a site and there is a function in JavaScript which its job is to do something based on a select input. it worked fine when i was developing the front but after replacing with Django form (Choice Input) it doesn't work. JavaScript code finds the element using id and I set {"id":"#idOfElement"}" in the (attrs). I can't understand where the problem is. any help is appreciated. -
Images in Django email template not loading in email
I'm using a template to send an email using Django. The email gets sent but the images are not displayed. In the template html file, I have: {% load static %} <img class="margin-bottom" height="52px" width="140px" src="{% static 'images/image.png' %}" /> In the settings.py file, I have the following: STATICFILES_DIRS = [os.path.join(BASE_DIR, "static")] STATIC_URL = env('STATIC_URL', cast=str, default='/static/') STATIC_ROOT = env( 'STATIC_ROOT', cast=str, default=os.path.join(BASE_DIR, "collected_static") ) And I have my images in a folder called images in the static folder. -
How to integrate Zoom services into a django website? [closed]
With a website project under construction, the need for 1-to-1 video calls arose. I have decided to use Zoom services for this purpose but I struggle to implement them. I would appreciate any general step-by-step guidance on this implementation process as well as any links to articles/videos/ etc on this topic. Any guidance will be a great help. -
please help me for customizing my django admin pannel
i should add this tables in my admin class in django please help me -
Can an empty ArrayField on Django Admin be saved?
models.py class BlogArticle(models.Model): # ... likers = ArrayField(models.GenericIPAddressField(), default=list) admin.py admin.site.register(BlogArticle) When using Django Admin page for an article with an empty list, the input is empty. This is ok to me, but when saving the object (after editing other fields for example), I get this error: It seems that it's interpreted as a None value, while to the current value is actually a valid empty list. Why would Django use the same way to represent empty list and a None value in the admin? I'm wondering if it's poorly designed or if I'm missing something here. Note that adding blank=True will make it worse, since it won't raise any error but will silently transform empty list to None. -
Unable to identify syntax error in Django's queryset
Unable to identify syntax error in Django's queryset. queryset = Orders.objects.exclude(created_by=created_by).values('id', 'property', 'units', 'created_by', 'sell_price_per_unit')filter(property=order_obj.property, order_type__name=BUY, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], buy_price_per_unit__gte=order_price).order_by('-buy_price_per_unit') Here is the compete traceback - Traceback (most recent call last): File "/usr/local/lib/python3.7/code.py", line 90, in runcode exec(code, self.locals) File "<console>", line 1, in <module> File "/ibdax/trade/utilities.py", line 29 queryset = Orders.objects.exclude(created_by=created_by).values('id', 'property', 'units', 'created_by', 'sell_price_per_unit')filter(property=order_obj.property, order_type__name=BUY, order_status__in=[PARTIALLY_COMPLETED[1], OPEN[1]], buy_price_per_unit__gte=order_price).order_by('- buy_price_per_unit') ^ SyntaxError: invalid syntax -
can anyone help me to figure out how to embed terminal to webpage so that I can take user input for programs written in webpage
I am working on online coding platform. As of now I am using subprocess module of python to run the program of other language and it's successfully also showing the output and as well as taking input from the code editor terminal of vs code . Basically it's interacting with the developmental code editor. but I need to make it interactive with web user i.e. when user write a code in web platform and click run then user should be able to enter the input from web platform. So, please can anyone help to figure out how to do that?