Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
I want to pass productid in my url so as to display details of only a specific product
this is how my django code looks like <a href="{% url 'product-details' product.id %}">Details</a> this is how my urls look like path('product/<int:id>/, views.product-details, name='product-details') after clicking on the link am getting this error noReverseMatch at /products/ what could be the problem with my code -
Heroku doesn't migrate models in Django
I have a Django app deployed on Heroku. I am trying to switch the database from mySQL to Postgres using the Heroku Postgres addon I erased all migrations and ran manage.py makemigrations to get a clean migration log. Then I commit and push. If I run manage.py migrate on my local machine, this is what I get: Migrations for 'manager': manager/migrations/0001_initial.py - Create model AbiMapping - Create model MissingContracts - Create model TempEmailAccounts - Create model UnsupportedMetaContracts - Create model Users - Create model Passwords - Create model ContractMapping - Create model Tokens I added this command to Procfile so migrate runs when I push to Heroku: release: python3 manage.py migrate When pushing to Heroku, the migrate call works but it doesn't migrate the models I have in the app: remote: Verifying deploy... done. remote: Running release command... remote: remote: Operations to perform: remote: Apply all migrations: admin, auth, contenttypes, manager, sessions remote: Running migrations: remote: No migrations to apply. This is how I setup the database is settings.py: .env sets environment variables on local machine. On heroku database environment variables are loaded from environment as there is not .env dotenv_file = os.path.join(BASE_DIR, ".env") if os.path.isfile(dotenv_file): dotenv.load_dotenv(dotenv_file) Setup database: DATABASES … -
How to perform live application update in Django server, without full shutdown?
Django has a very clear methodology how to update version of application code in the server(I.e deploy version): Make sure it works locally. Make migrations(could be additionally before 1) Shut down the server. Push code to the server. Migrate DB changes. Start the server again. But the big trouble is how to do this action without shutting down the server, so it will be still available to the users, even during update. Pinterest and Instantgram are both using Django, but you never saw them unavailable. What is the recommended or even a possible methodology? -
MultiValueDictKeyError 'name'
I have few apps in my project and now Im stuck with following problem, when Im filling up all fields and pressing "submit" then following error is showing: MultiValueDictKeyError at / 'name' Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 3.1.2 Exception Type: MultiValueDictKeyError Exception Value: 'name' Views form main directory(which is colliding name = request.POST['name']): def home(request): if request.method == 'POST': name = request.POST['name'] email = request.POST['email'] subject = request.POST['subject'] message = request.POST['message'] send_mail( 'message from' +' '+ name +' '+ email, message, email, ['blablablabla@gmail.com'], fail_silently=False, ) return render(request, 'wwwapp/home.html', {'name': name}) else: return render(request, 'wwwapp/home.html') I think with this views: def become_vendor(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): user = form.save() login(request, user) vendor = Vendor.objects.create(name=user.username, created_by=user) return redirect('frontpage') else: form = UserCreationForm() return render(request, 'vendor/become_vendor.html', {'form': form}) @login_required(login_url='loggin') def vendor_admin(request): vendor = request.user.vendor product = vendor.products.all() return render(request, 'vendor/vendor_admin.html', {'vendor': vendor, 'product': product}) @login_required def add_product(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.vendor = request.user.vendor product.slug = slugify(product.title) product.save() return redirect('vendor_admin') else: form = ProductForm() return render(request, 'vendor/add_product.html', {'form': form}) Forms for this Model: from django.forms import ModelForm from product.models import Product class ProductForm(ModelForm): class Meta: model … -
Display info from django database in a Map
j query vector map of Nigeria Good morning, please can i be given a tutorial on how to display information from my data base in a map? Its a django project. I want to for each state show its corresponding information in a tooltip format. -
I have the following problem when using autocomplete_fields field under django3.2
The following problems will occur!!! enter image description here When I use the version below django3.2, everything is normal. I don't know if this is my problem? And django will prompt the following error: During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\views\autocomplete.py", line 61, in process_request app_label = request.GET['app_label'] File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\utils\datastructures.py", line 78, in __getitem__ raise MultiValueDictKeyError(key) django.utils.datastructures.MultiValueDictKeyError: 'app_label' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\sites.py", line 250, in wrapper return self.admin_view(view, cacheable)(*args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\sites.py", line 232, in inner return view(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\sites.py", line 417, in autocomplete_view return AutocompleteJsonView.as_view(admin_site=self)(request) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\views\autocomplete.py", line 20, in get self.term, self.model_admin, self.source_field, to_field_name = self.process_request(request) File "C:\Users\admin\.virtualenvs\easyshow\lib\site-packages\django\contrib\admin\views\autocomplete.py", line 65, in process_request raise PermissionDenied from e django.core.exceptions.PermissionDenied -
How to run view.py file in Django in order to scrape and store data
I want to open and run a django project in pycharm. The project is about scrape data from another website by using beautifulsoup and selenium and store data to django database and show them in our own website. In order to launch scraping process when I run view.py file, I encounter the following error. File "C:\Users\XXXX\XXXXX\lib\site-packages\django\conf_init_.py", line 63, in _setup raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Can you please help me to figure out the issue. I struggled too much to solve the problem but could not solve that. I need to accomplish my task in a very limited time. I would be very grateful if anyone pioneer me to solve the issue -
Django doesn't show field
So, I'm new to django and I am learning I created a form but django doesn't show it in the page I am using python 3.9.4 django 3.2 this is my code models.py from django.db import models # Create your models here. class Commande(models.Model): name = models.CharField(max_length=300) forms.py from django import forms from .models import Commande class home_form(forms.ModelForm): class Meta: model = Commande fields = ['name'] class RawCmdForm(forms.Form): name = forms.CharField() views.py from .models import Commande from django.shortcuts import render from .forms import home_form, RawCmdForm # Create your views here. def home_view(request): medocs = Commande.objects.all() #print(medocs) context = {'medoc' : medocs} return render(request, "index.html", context) def cmd_Form_view(request): my_form = RawCmdForm() if request.method == "POST": my_form = RawCmdForm(request.POST) if my_form.is_valid(): print("Good Data") Commande.objects.create(**my_form.cleaned_data) my_form = RawCmdForm() #if request.method == "POST": # new_name= request.POST.get("name") # Medoc.objects.create(name = new_name) context = {"form" : my_form} return render(request, "index.html", context) index.html <!DOCTYPE html> <html> <head> <title>My Commande</title> </head> <body> <h1 style="color: red"> Mes Manqants</h1> {% for instance in medoc %} <input type="checkbox" id= {{instance.id}} name= {{instance.name}} value= {{instance.name}} > <label for= {{medoc.id}} > {{instance.name}} </label><br> {% endfor %} </body> </html> formadd.html {% extends "index.html" %} {% block content %} {{ form }} {% endblock %} … -
how to provide django key using .env file using Circle CI
I want to test my Django project in Circle CI. I came across few ways to set up .config file to do this but none of them mentioned how to set up for a django project using .env file to read keys I want a solution which doesn't require me to change my django project way of reading keys public .env file in my repo IDEAL SOLUTION I'M LOOKING FOR allows me to add keys via project key setup but doesn't require me to remove this line from my settings .py SECRET_KEY = env.str('SECRET_KEY') -
passing a list from jquery to a view function in django
Suppose I have the following function in my django project. getValues2() returns a list with numbers. How can I pass this numbers to my view using window.location? <script> let getValues2 = () => $("input[name='checkb']:checked").map((i,el) => el.id.trim()).get(); console.log('getValues2 ',getValues2()) window.location('eprint/checked' + getValues?() </script> views.py def eprint(request): print('eprint') # how to get the list from jquery? print(checked)