Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying to render data from database with a model in Django but it's showing operationError
Inside product app in views.py ''' from django.shortcuts import render from .models import Person def product_details(request,*args, **kwargs): obj=Person.objects.get(id=1) context={ 'object': obj } return render(request, "productH/detail.html", context) ''' Inside Templete I've made a new folder 'productH', and inside productH I made detail.html Inside detail.html ''' {% extends 'base.html' %} {% block content %} <h1> {{object.title}} </h1> <p> this is showing detail.html file </p> {% endblock %} ''' after this in url.py I've added ''' from Products.view import import person url={ path('product/', product_details) ''' inside model I've coded ''' [from django.db import models class Person(models.Model): first_name = models.CharField(max_length=30) middle_name = models.CharField(max_length=30, blank=True, null=True) last_name = models.CharField(max_length=30) roll_no = models.DecimalField(max_digits=3, decimal_places=0) total_marks = models.DecimalField(max_digits=4, decimal_places=2) ''' this Error is occuring. -
How can I pass my function inside my class model as a field?
I'm using the 3rd party library, Django Extensions, specifically for AutoSlugField(). I want to implement their use of RandomCharField() in my model for my slug field. from django_extensions.db.fields import AutoSlugField, RandomCharField class Post(models.Model): class BucketObjects(models.Manager): def get_queryset(self): return super().get_queryset() ... #unique_string = RandomCharField(length=10, unique=True) slug = AutoSlugField(populate_from = models.random_string(), blank=True) ... objects = models.Manager() bucketobjects = BucketObjects() def random_string(self): unique_characters = RandomCharField(length=10, unique=True) self.slug = unique_characters self.save() def __unicode__(self): return self.stock_list AutoSlugField requires the populate_from parameter. Passing RandomCharField() like so: slug = AutoSlugField(populate_from = RandomCharField(), ...) Does not work: TypeError: 'populate_from' must be str or list[str] or tuple[str], found <django_extensions.db.fields.RandomCharField> So instead I want to make a function within my class that creates and saves a RandomCharField to my slug field. In the model above, you can see I commented out unique_string, if I pass that field to my populate_from parameter, then everything works fine. But it seems a redundant and a waste of space to have two model fields that are exactly the same. How can I pass my random_string function to my slug populate_from parameter whenever a Post is created? Thank you for the help. -
Reload a bootstrap toast
I have a bootstrap toast to inform user a successful form submission with Ajax. Message is generated in Django view. How Can i reload the toast to show New messages? I tried to reload the entire div but the data-delay doesn't work anymore. -
How to control developers so that only part of modules are assigned to them?
I have a question, what is the best way to control the code to developers? I have a project in development with 5 people, who work collaboratively (Git), but I don't want everyone to see the complete code, if not only one person has control and the others only the parts / modules assigned to them. In the project we use VSCode, Django, with Git. -
django template filter throws decimal.InvalidOperation although the exception is handled
From the server log, decimal.InvalidOperation exception is thrown: "......django/template/defaultfilters.py", line 138, in floatformat d = Decimal(input_val) decimal.InvalidOperation: [<class 'decimal.ConversionSyntax'>] But the InvalidOperation is actually handled in the django floatformat filter: try: input_val = repr(text) d = Decimal(input_val) except UnicodeEncodeError: return '' except InvalidOperation: if input_val in special_floats: return input_val try: d = Decimal(force_text(float(text))) except (ValueError, InvalidOperation, TypeError, UnicodeEncodeError): return '' I cannot duplicate the situation, but can see that the error is thrown on server all the time. It happens after upgrading python from 3.7 to 3.9, django version unchanged. Any idea why the floatformat template filter would throw an already handled exception? Thanks. -
How to access the Django app running inside the Docker container?
I am currently running my django app inside the docker container by using the below command docker-compose run app sh -c "python manage.py runserver" but I am not able to access the app with local host url, (not using any additional db server or ngnix or gunicorn, just simply running the django devlopment server inside the docker). please let me know how to access the app -
Field 'Product_id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x0000022D29594848>'
Hello trying to save data and display it on my cart using django. Its giving me an value error when i try to add a product to cart. The error message is: Field 'Product_id' expected a number but got '<django.db.models.query_utils.DeferredAttribute object at 0x0000022D29594848>'. here is my cart file source code: from decimal import Decimal from django.conf import settings from store.models import Product class Cart(object): def __init__(self, request): """ Initialize the cart. """ self.session = request.session cart = self.session.get(settings.CART_SESSION_ID) if not cart: # save an empty cart in the session cart = self.session[settings.CART_SESSION_ID] = {} self.cart = cart def __iter__(self): """ Iterate over the items in the cart and get the products from the database. """ product_ids = self.cart.keys() # get the product objects and add them to the cart products = Product.objects.filter(Product_id__in=product_ids) cart = self.cart.copy() for product in products: cart[str(product.Product_id)]['product'] = product for item in cart.values(): item['Price'] = Decimal(item['Price']) item['total_price'] = item['Price'] * item['Quantity'] yield item def __len__(self): """ Count all items in the cart. """ return sum(item['Quantity'] for item in self.cart.values()) def add(self, product, quantity=1, override_quantity=False): """ Add a product to the cart or update its quantity. """ product_id = str(product.Product_id) if product_id not in self.cart: self.cart[product_id] = {'quantity': … -
How to clean up downloaded files in Django view testing?
I have a Django view that returns a file to download (response['Content-Disposition'] = 'attachment; filename=' + filename) in response to a POST as the contents of the file are dependent on data submitted by a form. In setting up my tests for this view, I'm having a hard time finding a clean way to download the file and make sure it is cleaned up afterwards as this doesn't come for free with the TestCase behavior. Currently I have the following: with tempfile.TemporaryDirectory(dir='.') as temp_dir: os.chdir(temp_dir) response = self.client.post(...) # Do asserts of the downloaded file/response object here os.chdir('..') This has the benefit of creating a temporary directory where the file is downloaded to, and the whole directory is deleted when the test completes. Also, if any of the asserts fail the temp directory (and contents) will stick around, but this specifically feels fragile and like it could break other tests because of the directory change. Is there a better way/pattern to accomplish this? -
Django Website <button /> tags do not work on firefox web browser
I have created a read more js event for my django app. To fire the event there is a button with onclick="myFunction()" in the button tag of the html. The issue I am having is on Firefox. I can't click any buttons or any links on the django app/website. AT ALL. This is only the case for my django app, other website works perfectly. When clicking the button nothing comes up in the console. It is almost as if the browser doesnt even see the button or any menu links. Safari and Chrome everything works normally. Thank you for your time and responses! -
Django - De-compose bcrypt hashed password
I want Django to use the Bcrypt algorithm to hash my password. The result looks like this: bcrypt_sha256$$2b$12$JWIEqA1.FnHvaymy2vrGcexFbglZ4qdTlJ9fFNTbAy87VYvwmNwYa Django says that the password is stored in the form of: <algorithm>$<iterations>$<salt>$<hash> But it does not really seem consistent with the result. I need to get the salt from the previous result, do you know wich part it is ? Thank you. -
Output query result into table in Django
I currently have PHP scripts that run a query against a MySQL database and display the results in a table. I want to be able to replicate this in Django, but I am having difficulty in outputting the row data. I would eventually like to use Datatables to output the results, however I am having difficulty getting the results in just a basic table. Most of the MySQL queries are not straight-forward and involve various joins, subqueries, calculations etc and I'm confused on how to have this complexity in Django. Is is easier to use connection to send raw SQL? #models.py from django.db import models class Author(models.Model): name = models.CharField(max_length=200) email = models.CharField(max_length=200) class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') author_id = models.ForeignKey(Author, on_delete=models.CASCADE) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) #views.py from django.shortcuts import render from .models import Question def index(request): row_data = Question.objects.values('question_text', 'pub_date', 'author__name', 'author__email', 'choice__votes') context = {'row_data': row_data} return render(request, 'datatable/index.html', context) #templates/datatable/index.html {% if row_data %} <table> <tr> <th> Question text </th> <th> Pub date </th> <th> Author name </th> <th> Email </th> <th> Votes </th> </tr> {% for question in row_data %} <tr> <td>{{ question.question_text }}</td> … -
Error retrieving access token: b'{\n "error": "redirect_uri_mismatch",\n "error_description": "Bad Request"\n}'
Trying to authenticate from Nuxt App using Django rest + allauth + dj-rest-auth First Error allauth.socialaccount.models.SocialApp.DoesNotExist: SocialApp matching query does not exist. resolved this by changing SITE_ID = 1 TO 2 Second I am getting This error Traceback (most recent call last): File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\xyz\django-env\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\generic\base.py", line 71, in view return self.dispatch(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\utils\decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\django\views\decorators\debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\views.py", line 48, in dispatch return super(LoginView, self).dispatch(*args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 509, in dispatch response = self.handle_exception(exc) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 469, in handle_exception self.raise_uncaught_exception(exc) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 480, in raise_uncaught_exception raise exc File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\views.py", line 506, in dispatch response = handler(request, *args, **kwargs) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\views.py", line 138, in post self.serializer.is_valid(raise_exception=True) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\serializers.py", line 220, in is_valid self._validated_data = self.run_validation(self.initial_data) File "C:\Users\xyz\django-env\lib\site-packages\rest_framework\serializers.py", line 422, in run_validation value = self.validate(value) File "C:\Users\xyz\django-env\lib\site-packages\dj_rest_auth\registration\serializers.py", line 117, in validate token = client.get_access_token(code) File "C:\Users\xyz\django-env\lib\site-packages\allauth\socialaccount\providers\oauth2\client.py", line 91, in get_access_token raise OAuth2Error("Error retrieving access token: … -
change django view context based on template
I'm wondering if there is a way to change django view context based on template (I've no idea if it's possible) I'm building a chat application where I loop through all the thread messages and I'm looping through all images that if the image message id equals to message id to show the message related image. It's something like this .. {% for message in chatmessages %} <p>{{ message.message }}</p> {% for img in images %} {% if img.message.id == message.id %} <img src="{{ img.image.url }}"> {% endif %} {% endfor %} {% endfor %} and the same for attachments. I'm sending these context from my view context = { "me": me, "threads": threads, "other_user": other_user, "chatmessages": ChatMessage.objects.filter(thread=thread.id), "images": MultipleImage.objects.all(), "attachments": MultipleAttchment.objects.all(), } Any better way to reduce my looping in template for a better functionality. here is my models.py ... class ChatMessage(models.Model): thread = models.ForeignKey(Thread, null=True, blank=True, on_delete=models.SET_NULL) user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) message = models.TextField(null=True) timestamp = models.DateTimeField(auto_now_add=True) voice = models.FileField(upload_to=upload_voice_dir, blank=True, null=True) class MultipleImage(models.Model): message = models.ForeignKey('ChatMessage', on_delete=models.CASCADE) image = models.ImageField(upload_to=upload_img_dir, blank=True, null=True) class MultipleAttchment(models.Model): message = models.ForeignKey(ChatMessage, on_delete=models.CASCADE) attachment = models.FileField(upload_to=upload_att_dir, blank=True, null=True) ... looking for a better way :( -
how to change innerHTML using classname inside loop
here my code i just wanna change the innerHTML of btn by grabbing classname which is inside for loop {% for pbyid in productbyid %} <div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'> <div> <div> <a href="/viewpage/{{pbyid.id}}"><div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div></a> <span class="top-left">{{pbyid.discountpercentage}}% off</span> </div> <div class="card-body"> <h5 class="card-title cardtitle">{{pbyid.title}}</h5> <div><p class="carddesccrip">{{pbyid.desc}} </p></div> <div class='pricce_card'> <span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span> <span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span> </div> </div> <div class="card-body"> {% comment %} /viewpage/{{pbyid.id}} {% endcomment %} <p href="" id='' class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction({{pbyid.id}})" > Add to cart <i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></p> </div> </div> </div> {% endfor %} js how can i change html of btn from class , when i try it doesn't wok with classname but it work with id , but for id is specific so we have to use classname but i'm not exactly getting how to solve can anyone have idea to solve it function myFunction(id) { var x = document.getElementsByClassName("caddtocart"); x.innerHTML = "added"; console.log(id); } </script> -
Mac filtering on Django?
Is there a package or how to?, on Django that allows to whitelist a mac address that stored on a model. class mac_address(models.Model): mac_address = models.CharField(max_length=17) That only listed mac addresses are only able to access the webapp, since IP whitelisting is kinda complicated because it's changes from time to time. -
Django - Annotate with first filtered related object
Having models: class Book(models.Model): name = models.CharField(max_length=255) class Page(models.Model): text = models.TextField() page_number = models.PositiveSmallIntegerField() book = models.ForeignKey(Book, on_delete=models.CASCADE) I want to annotate books with selected_page based on changing page number, books that doesn't have required page number will have book.selected_page = None: page_number = get_page_number() books = Book.objects.annotate(???) # smthing like: Book.objects.annotate(selected_page=Page.objects.filter(page_number=page_number)) for book in books: if book.selected_page: print(book.selected_page.text) -
Cannot use 'in' operator to search for 'length' in 'id_cliente'
I am trying to add the sale of products to the database but it turns out that when I try to do it I get the following error: jquery.min.js:2 Uncaught TypeError: Cannot use 'in' operator to search for 'length' in 'id_cliente' I had to add some lines to the ajax code because otherwise another error would appear I hope you can help me JS $('form').on('submit', function (e) { e.preventDefault(); ventas.items.id_cliente = $('input[name="id_cliente"]').val(); ventas.items.fecha_venta = $('input[name="fecha_venta"]').val(); ventas.items.forma_pago = $('input[name="forma_pago"]').val(); ventas.items.precio_total = $('input[name="precio_total"]').val(); var parametros = new FormData(); parametros.append('action', $('input[name="action"]').val()); parametros.append('ventas', JSON.stringify(ventas.items)); submit(window.location.pathname, parametros, function () { location.href = 'crear_venta'; }); Views def post(self, request, *args, **kwargs): data = {} try: action = request.POST['action'] if action == 'autocomplete': productos = Producto.objects.filter( nombre__icontains=request.POST['term'])[0:10] for i in productos: data = [] item = i.toJSON() item['value'] = i.nombre data.append(item) elif action == 'add': #vents = request.POST['ventas'] ventas = json.loads(request.POST['ventas']) print(ventas) venta = Venta() venta.id_cliente = int(ventas['id_cliente']) venta.id_empleado = int(ventas['id_empleado']) venta.fecha_venta = ventas['fecha_venta'] venta.forma_pago = ventas['forma_pago'] venta.precio_total = float(ventas['precio_total']) venta.save() for i in ventas['productos']: detalle_venta = Detalle_Venta() detalle_venta.id_detalle_venta = venta.id_venta detalle_venta.id_producto = int(i['id_producto']) detalle_venta.cantidad = int(i['cantidad']) detalle_venta.subtotal = float(i['subtotal']) detalle_venta.save() else: data['error'] = 'No ha ingresado a ninguna opción' except Exception as e: data['error'] = str(e) … -
How to correctly represent a "warehouse" in django - n+1 problems
I'm learning Django. I am trying to make an app for managin a warehouse that's composed by simple elements: Involved models are transaction, items, warehouses and homes. models.py: class Home(Model): name = models.CharField(max_length=255, verbose_name=_('name'),blank=False) class Warehouse(Model): name = models.CharField(max_length=255, verbose_name=_('name'),blank=False) class Item(Model): name = models.CharField(max_length=255, verbose_name=_('name'), whouse = models.ForeignKey('Warehouse', blank=True,null=True,on_delete=models.CASCADE, related_name='all_items') quantity = models.PositiveSmallIntegerField(verbose_name=_('Quantity'), default=1, blank=False) @cached_property def count_remaining(self): remaining = self.quantity qs = self.transactions.all() if qs: out = qs.aggregate(Sum('quantity'))['quantity__sum'] if out: remaining -= out return remaining class Transaction(Model): item_field = models.ForeignKey('Item', blank=True,null=True,on_delete=models.CASCADE, related_name='all_transactions') home_field = models.ForeignKey('Home', blank=True,null=True,on_delete=models.CASCADE, related_name='all_transactions') quantity = models.PositiveSmallIntegerField(verbose_name=_('Quantity'), default=1, blank=False) item_list.html (for the generic ListView, with qs=Item.objects.all()): ... <table> <thead> <tr> <td>name</td> <td>quantity</td> <td>remaining items</td> <td>whouse</td> </tr> </thead> <tbody> {% for item in item_list %} <td>{{ item.name }}</td> <td>{{ item.quantity }}</td> <td>{{ item.count_remaining }}</td> <td>{{ item.whouse }}</td> {% endfor %} </tbody> </table> ... Now my problem is that my count_remaining method is being called one time for each object in the queryset, obviously resulting in an exponential number of database hits when there are many items in item_list. How can I make this arithmetical operation without hitting the db so much, provided that I must have a page that displays in the template the remaining items … -
Why I am getting Error 404 at Admin /Django
How can I fix this error: Page not found (404) You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. It's my urls.py file: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('',include('pages.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
django, How to filter this case?
class SomeConnect(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='sc_user') some = models.ForeignKey(Some, on_delete=models.CASCADE, null=True, blank=True, related_name='sc_some') class UserFollow(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True, related_name='c_user1') user2 = models.ForeignKey(Some, on_delete=models.CASCADE, null=True, blank=True, related_name='c_user2') I want to find User Queryset on condition: User.objects.filter(someconnect's some is some1, someconnect's user=user_connect's user1 and user1 is followed by user2 has priority) example) In this case, UserFollow's user2 is kippling someconnect1 -> (user is jessica1, some is food) userfollow -> (user1 is jessica1, user2 is kippling) someconnect2 -> (user is jessica2, some is food) userfollow -> (user1 is jessica2, user2 is no_kippling) #Here is different someconnect3 -> (user is jessica3, some is food) userfollow -> (user1 is jessica3, user2 is kippling) so that I want to get queryset like(jessica1, jessica3, jessica2) Because jessica is not followed by kippling but no_kippling. How to filter it? -
Frequency of Django settings loading and initialization in a uSWGI + Django setup
I have a Django app running with uWSGI and wanted to understand how Django settings are loaded and re-initialized. uWSGI config has the following settings: ... max-requests = 5000 workers = 8 enable-threads = true ... So in terms Django settings (and the whole app for that matter), do the settings get initialized once every 5000 requests when a worker is being recreated ? -
Is it good practice to add .git folder to Github?
After i entered git init I have directory D:myproject\.git Is it good to add .git folder it in Github or should i add it in .gitignore? -
Interlinking records in a many-to-many field doesn't appear toaccept multiple records
I have this model for a tune: class MsTune(models.Model): name = models.CharField(max_length=255) ms = models.ForeignKey(Manuscript, on_delete=models.CASCADE, related_name="mstunes") concordances = models.ManyToManyField("self", blank=True) I have many manuscripts (ms), and the same tune might appear in more than one manuscript. What I want to do, with that concordances field, is link all the similar tunes. This works, in part. The Django administration back-end allows me to select many tunes to be linked to the current one I'm editing: The problem is that I'd like to see ALL the tunes I've linked in each of the tune. For instance, in the example above, Mary Scott... should list all three tunes (Courante, Almain, Hopetounsetc...); Courante should list the other three (Mary Scott, Almain, Hopetoun's). Right now they only show one. What am I missing? Do I have to create a new concordances model? -
How to limit calls to external API in django
I have an app that displays all the posts of a YouTube-Channel. For that, I use the youtube-API v3 which I call in my views.py. I then save all the data in my database which I pass as context to my render-function: return render(request, "blog/home.html", context) I was wondering if it's possible to only call the API if the last API-call was 5 minutes ago and just use the data in the database otherwise. One idea I have is to save the current datetime to a file whenever an API-call is made, and whenever the views-function is called, compare the current datetime with the one in the file. However, this seems inefficient and I was wondering if there was a better way. -
Visual tree representation After filtering
I'm working on a Django app, I want to make some kind of tree of nodes and leafs like this example. How I can implement that using html-css-javascript ? Is there any library or framework that helps ?