Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When i want to add a product to my cart i have a keyerror
When i click add to cart i have the following error in views.py: "In updateItem, productId = data['productId'] KeyError: 'productId' " views.py line 70 where i have my error: def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('productId:', productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = OrderItem.objects.get_or_create(order = order, product = product) if action == 'add': orderItem.quantity = (orderItem.quantity +1) elif action == 'remove': orderItem.quantity = (orderItem.quantity -1) orderItem.save() if orderItem.quantity <=0: orderItem.delete() return JsonResponse('El item fue agregado', safe=False) carrito.js: function updateUserOrder(productId, action){ console.log('Usuario logeado y enviando data...') var url = '/update_item/' fetch (url, { method: 'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId': productId, 'action':action}) }) .then((response) =>{ return response.json() }) .then((data) =>{ console.log('data:', data) location.reload() }) } My template carrito.html: When i click on the button Add to cart i have the issue. {% extends 'tienda/index.html' %} {% load static %} {% block content %} </div> {% for item in items %} <div class="cart-row"> <div style="flex:2"><img class="row-image" src="{{item.product.imageURL}}"></div> <div style="flex:2"><p>{{item.product.name}}</p></div> <div style="flex:1"><p>{{item.product.price|floatformat:2}}</p></div> <div style="flex:1"> <p class="quantity">{{item.quantity}}</p> <div class="quantity"> <img data-product={{item.product.id}} data-action="add" class="chg-quantity update-cart" src="{% static 'images/arrow-up.png' %}"> <img data-product={{item.product.id}} data-action="remove" class="chg-quantity update-cart" src="{% static 'images/arrow-down.png' %}"> </div> … -
Django queryset join two or more models that use the same foreign key or have nested relationships
I want to get an aggregated data related to each Tree entry. from django.db import models class Tree(models.Model): tree_name = models.CharField(max_length=100, unique=True) class Branch(models.Model): tree = models.ForeignKey(Tree, on_delete=models.CASCADE) branch_type = models.ForeignKey(BranchType, on_delete=models.CASCADE) branch_health = models.ForeignKey(AppConfig, on_delete=models.CASCADE) last_checked = models.DateTimeField(null=False) class BranchType(models.Model): type_name = models.CharField(max_length=30, unique=True) class Stump(models.Model): tree = models.OneToOneField(Tree, on_delete=models.CASCADE) stump_info = models.ForeignKey(StumpInfo, on_delete=models.CASCADE) class StumpInfo(models.Model): scientific_term = models.CharField(max_length=100, unique=True) class AppConfig(models.Model): key = models.CharField(max_length=100, unique=True) value = models.CharField(max_length=100) The output I am looking for is something like this: [ { "tree": "ucxdfg", "branch": {// The tree can have a lot of branches, but I only target branches from past 24 hours. "branch_type_1": "average",// The health is coming from app_config ["good","average", "poor"] "branch_type_2": "good" }, "stump_info": { "scientific_term": "xyz" } }, { "tree": "awerdf", "branch": { "branch_type_1": "good" }, "stump_info": { "scientific_term": "xyz" } }, { "tree": "powejf", "branch": { "branch_type_2": "poor" }, "stump_info": { "scientific_term": "abc" } }, ... ] I am not sure how I would design the queryset to do this. -
Dynamic Queryset Based on Special Model Django
I would like to have a page that contains product and related competitor products with it. I tried, but all the times competitor products stay same. Would you please help me? models: class Product(models.Model): created_by = models.ForeignKey(User, on_delete=models.CASCADE) category = models.CharField(max_length=120) brand = models.CharField(max_length=120) product = models.CharField(max_length=120) price = models.DecimalField(decimal_places=2,max_digits=100) class Comp_Product(models.Model): product = models.ForeignKey(Product,on_delete=models.CASCADE) competitor = models.URLField() price = models.DecimalField(decimal_places=2,max_digits=100) change = models.FloatField() stock = models.BooleanField() last_update = models.DateField(auto_now_add=True) views: class ProductListView (ListView): model = Comp_Product context_object_name = 'comp_products' template_name = 'products.html' class ProductDetailView (LoginRequiredMixin,DetailView): model = Product template_name = 'product.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['comp_products'] = Comp_Product.objects.all() return context urls.py: path('product/<int:pk>/', ProductDetailView.as_view(),name='product_detail'), path('comp_products/', ProductListView.as_view(),name='comp_products'), -
Django rest-framwork [views]: users can update only modules they created
So I have a view for my Django app that is used to update/delete user profiles. I'm wondering is there a better way to check if the person who's requesting the change is the same one that's in the url. request url looks like this /profile/<str:username> class UserDetail(RetrieveUpdateDestroyAPIView): queryset = User.objects.all() serializer_class = UserSerializerFull permission_classes = [IsAuthenticated] lookup_field = "username" def put(self, request, *args, **kwargs): if str(request.user) == kwargs.get("username"): return super().put(request, *args, **kwargs) return Response( data={"msg": "unauthorized request"}, status=status.HTTP_403_FORBIDDEN ) def patch(self, request, *args, **kwargs): if str(request.user) == kwargs.get("username"): return super().patch(request, *args, **kwargs) return Response( data={"msg": "unauthorized request"}, status=status.HTTP_403_FORBIDDEN ) def delete(self, request, *args, **kwargs): if str(request.user) == kwargs.get("username"): return super().delete(request, *args, **kwargs) return Response( data={"msg": "unauthorized request"}, status=status.HTTP_403_FORBIDDEN ) As all of the methods are repeating the same code is there a way to write something just for once and use it everywhere. Also for other models that are made by the User profile i have the same issue as a lot of the code is repeating itself. -
How to use Django iterator in this case
I want to show 20 reviews per page on my website. Unfortunately whole reviews count is about 260,000, It takes 3~4sec to show at page 10,000~ I used to use queryset like this: reviews = Review.objects.all()[(page_num-1)*20:20*page_num] . . . obj['reviews'] = reviews Now I think using iterator(chunk_size=) is better than upper one for efficiency. But I dont know how to use iterator() properly. I definitely need your helps Please let me know... -
store.models.CartQuantity.DoesNotExist: CartQuantity matching query does not exist
Hi I'm trying to get the newest/latest number in a query set: I use this codeline for that: CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True).get(pk=-1) This is how the queryset looks like: <bound method QuerySet.last of <QuerySet [4, 4, 4, 2, 4, 4, 5, 6, 5, 14, 10, 12]>> # need last number(12) I tried the code above but I get an Error message: store.models.CartQuantity.DoesNotExist: CartQuantity matching query does not exist. This is my models: class CartQuantity(models.Model): customer = models.ForeignKey(Customer, on_delete=models.SET_NULL, blank=True, null=True) cquantity = models.IntegerField(default=0, null=True, blank=True) Does anyone know how to fix the error or another way of getting the newest number(in this case number 12 in the query set)? -
AWS Elastic Beanstalk Python Django S3 Access Denied cannot upload / read file
I have deployed Python Django server on AWS Elastic Beanstalk. This is how my settings.py file looks like: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = None AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') # s3 public media settings PUBLIC_MEDIA_LOCATION = 'media' MEDIA_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{PUBLIC_MEDIA_LOCATION}/' DEFAULT_FILE_STORAGE = 'hello_django.storage_backends.PublicMediaStorage' # s3 private media settings PRIVATE_MEDIA_LOCATION = 'private' PRIVATE_FILE_STORAGE = 'hello_django.storage_backends.PrivateMediaStorage' In AWS I created IAM user with AmazonS3FullAccess permission, and I use his AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY in settings. The problem is that when I try to read media file from the file link I always get "Access denied" error, even if I specify PublicMediaStorage and give all public access on S3 bucket. Also, when I upload file, the folder (e.g 'media') in bucket does not get created. Do you have idea what could the problem ? -
Django: How to get an object with a file name
Let's say I have a model with a FileField: class Foo(models.Model): file = models.FileField( upload_to='files' ) What would be the best approach for getting an object from the model with the name of the file? Something like: try: foo = Foo.objects.get( file__name='bar.csv', ) except Foo.MultipleObjectsReturned: return something() except Foo.DoesNotExist: return something_else() process(foo) I guess I could add a file_name field into the model, but that seems cumbersome..? -
Error while running server in django after connecting djangorestframework
This error happens after adding rest_framework (pip install djangorestframework) to project but i dont know the reason in this framework or not. Error log, i think, is not enough informative for me. If need to share any file just let me know. Note: I am new in django web api so any your advice would be valuable. Thank you in advance. Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\commands\runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 76, in raise_last_exception raise _exception[1] File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\management\__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\registry.py", line 91, in populate app_config = AppConfig.create(entry) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\site-packages\django\apps\config.py", line 90, in create module = import_module(entry) File "C:\Users\fuadt\AppData\Local\Programs\Python\Python38\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 973, in _find_and_load_unlocked ModuleNotFoundError: No module named 'rest_framework' Traceback (most recent call last): File "manage.py", line 22, in … -
Am using drf-spectacular for my Django rest api documentation, how to override our own endpoint
In below code am not able to generate schema for 2 endpoints admin/ and payslip/ urlpatterns = [ # YOUR PATTERNS path('admin/', admin.site.urls),, path('payslip/',include('payslip.urls')) path('api/schema/', SpectacularAPIView.as_view(), name='schema'), # Optional UI: path('api/schema/swagger-ui/', SpectacularSwaggerView.as_view(url_name='schema'), name='swagger-ui'), path('api/schema/redoc/', SpectacularRedocView.as_view(url_name='schema'), name='redoc'), ] -
Django-filter, multiple fields search overriding other parameters! (django-filter)
I am having a spot of trouble making a search box that looks through both the title, and the description of the model, without it over riding everything. I took my example from this: Django-filter, how to make multiple fields search? (with django-filter!) so my current filter looks something like: class QuestionSetFilter(django_filters.FilterSet): search = CharFilter(method='my_custom_filter', label='search') o = OrderingFilter( fields = ( ('date_posted', 'date_posted') ), choices = [ ('date_posted', 'Old first'), ('-date_posted', 'New first'), ] ) class Meta: model = QuestionSet exclude = ['image', 'user', 'date_posted', 'question_set_description', 'question_set_title'] def my_custom_filter(self, queryset, name, value): return QuestionSet.objects.filter( Q(question_set_title__icontains=value) | Q(question_set_description__icontains=value) ) How can I change my custom filter to still chain with the other parameters I want to search with? -
Django urls "overlapping"
Ok. Hi guys. I googled this problem and didn't find anything that would help. Ok so this is my project structure: -myproject -controlpanel -urls.py -views.py -templates -controlpanel -index.html -include -navbar.html -main -urls.py -views.py -templates -main -index.html -partials -navbar.html -myproject -urls.py This is my controlpanel urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('servers', views.servers, name='servers'), ] This is my main urls.py file: from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('join', views.join, name='join'), path('rules', views.rules, name='rules'), path('services', views.services, name='services'), path('stats', views.stats, name='stats'), path('gdpr', views.gdpr, name='gdpr'), path('login', views.login, name='login'), ] This is myproject urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('', include('main.urls')), path('controlpanel/', include('controlpanel.urls')), path('admin/', admin.site.urls), ] Now when user doesn't specify any subdirectory he should be redirected to index.html in app main. The problem is that some {% url 'urlname' %} return urls from other projects. For instance when i used {% url 'index' %} in main apps navbar it used url controlpanel/index which it isn't supposed to do. This also happened to me when i was creating navbar for controlpanel and imported css but i solved it by renaming … -
How can i sort event by current user in Django calendar
I have a problem with sorting events in the Django calendar, namely, I would like to filter them not only by date but also by the user who created the event so that only his events are displayed on the calendar and not other users this is my utils.py file class Calendar(LocaleHTMLCalendar): def __init__(self, year=None, month=None): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' for event in events_per_day: d += f'<li> {event.get_html_url} </li>' if day != 0: return f"<td><span class='date'>{day}</span><ul> {d} </ul></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' for d, weekday in theweek: week += self.formatday(d, events) print() return f'<tr> {week} </tr>' # formats a month as a table # filter events by year and month def formatmonth(self, withyear=True,): events = Event.objects.filter(start_time__year=self.year, start_time__month=self.month,) cal = f'<table border="0" cellpadding="0" cellspacing="0" class="calendar">\n' cal += f'{self.formatmonthname(self.year, self.month, withyear=withyear)}\n' cal += f'{self.formatweekheader()}\n' for week in self.monthdays2calendar(self.year, self.month): cal += f'{self.formatweek(week, events)}\n' return cal My problem is that I do not know how to apply filtering with the current user in the object … -
Django - How can I implement and ignore case-sensitivity within my model to make the fields unique by character only?
How can I implement a function or method for my username and email fields to ignore case-sensitivity. By current Django standard, both the name John and john are unique by default. I want the mentioned fields to be unique by characters only, ignoring any aspect of captial cases. Is there any simple way of doing this? I want to do this at the database level, so I don't have to constantly repeat hacky code whenever I want to implement. I found this thread: Case insensitive unique model fields in Django? The first answer, creating an SQL index option has me worried because indexes need to be maintained and an index is not always used for a query. Then there's another method that uses citext , the docs mention that this is only possible during first create table migration, that seems like the most simple option, but it requires the most maintaince if you already have a live db. The next option for ease would probably be this method referenced: class MyModelManager(models.Manager): def get_by_username(self, username): return self.get(username__iexact=username) class MyModel(models.Model): ... objects = MyModelManager() I would like to try and replicate that using my model: class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), … -
Displaying fields not intended to be edited in ModelAdmin
I have a custom contact form for which I create a sent_time field using auto_now_add to save the time when the user had sent the message. I am able to list all the information on the listing view of the admin panel however when I try to enter a specific message I hit the following error: 'sent_time' cannot be specified for GeneralContact model form as it is a non-editable field My attempt to make the fields readonly in the ModelAdmin results in the same error class GeneralContactAdmin(ModelAdmin): """ Admin model for general correspondence via the main contact form on the information page """ model = GeneralContact list_display = GeneralContact.__all__ search_fields = GeneralContact.__all__ readonly_fields = GeneralContact.__all__ ordering = ('-sent_time',) list_filter = ('sent_time', 'has_response') Surely it is possible to be displayed only, perhaps I've done something incorrectly in my models? Here is the base model I use for the contact model class ContactFormBase(models.Model): __all__ = ( 'sent_time', 'sender_name', 'sender_email', 'sender_message', 'has_response', 'responded_on' ) sent_time = models.DateTimeField(auto_now_add=True) sender_name = models.CharField() sender_email = models.EmailField() sender_message = models.TextField() has_response = models.BooleanField( default=False, help_text='Select whether this message has been replied to by an admin.', ) responded_on = models.DateTimeField(blank=True, null=True) panels = [ FieldRowPanel([ FieldPanel('sender_name'), FieldPanel('sender_email'), ]), … -
Logging not working within WebSocketConsumer sub-classes
I have an issue where logging statements are not working in subclasses of WebsocketConsumer. Logger works in the entry point to the daphne application and even above the class declaration but not within the consumer. logger = logging.getLogger(name) logger.info("This log shows up") class TrackNotifyConsumer(WebsocketConsumer): """API Tracking Notifications Consumer""" def connect(self): logger.info("This log DOES NOT show up") async_to_sync(self.channel_layer.group_add)("track", self.channel_name) self.accept() Your OS and runtime environment, and browser if applicable Ubuntu 18.04.4 LTS A pip freeze output: freeze.txt This is deployed via Daphne, nginx -
Celery beat stuck on starting with Django and Redis
In my Django project I have two tasks in two different apps that I want to run periodically with Celery. The worker seems to collect the tasks and the beat seems to collect the schedular. However, the beat stuck on starting (it didn't synchronize the schedules) and never deliver the tasks to the worker. The celery --app=bozonaro worker --loglevel=debug --beat (bozonaro is my django project's name) command prompts the following to me: [2021-02-04 18:23:48,080: DEBUG/MainProcess] | Worker: Preparing bootsteps. [2021-02-04 18:23:48,103: DEBUG/MainProcess] | Worker: Building graph... [2021-02-04 18:23:48,104: DEBUG/MainProcess] | Worker: New boot order: {Timer, Hub, Pool, Autoscaler, StateDB, Beat, Consumer} [2021-02-04 18:23:48,257: DEBUG/MainProcess] | Consumer: Preparing bootsteps. [2021-02-04 18:23:48,257: DEBUG/MainProcess] | Consumer: Building graph... [2021-02-04 18:23:48,413: DEBUG/MainProcess] | Consumer: New boot order: {Connection, Events, Heart, Agent, Mingle, Gossip, Tasks, Control, event loop} -------------- celery@LAPTOP-E5L3SQ6N v5.0.5 (singularity) --- ***** ----- -- ******* ---- Linux-4.19.128-microsoft-standard-x86_64-with-glibc2.29 2021-02-04 18:23:48 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: bozonaro:0x7fc00b16d4c0 - ** ---------- .> transport: redis://localhost:6379// - ** ---------- .> results: redis://localhost:6379/ - *** --- * --- .> concurrency: 8 (prefork) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- … -
Django DecimalField Formatting and Filtering Non-Responsive
The DecimalField output on my template is appearing like this; Total Cost: {'Cost__sum': Decimal('739.900000000000')} when it should appear like this Total Cost: 739.90. Despite my model only having 2 decimal places and trying the DecimalField filters the formatting does not change, it also includes my context variable 'Cost__Sum'. This has not happened in previous apps despite using the same code. Greatly appreciate if someone could point out what is going wrong here. Model.py class ComicInput(models.Model): Cost = models.DecimalField(max_digits=10, decimal_places=2, default='1.95') Value = models.DecimalField(max_digits=10, decimal_places=2, default='1.95') SoldAmt = models.DecimalField(max_digits=10, decimal_places=2, default='0.00') Views.py def home(self): """Renders the home page.""" #excludelist = ('Sold','Wish') if self.user.is_authenticated: DisplaySumCost=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('Cost')) DisplaySumValue=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('Value')) DisplaySumSoldAmt=ComicInput.objects.all().filter( uid=self.user).aggregate(Sum('SoldAmt')) assert isinstance(self, HttpRequest) return render( self, 'app/index.html', { 'title':'Kollector', 'year':datetime.now().year, 'DisplaySumValue': DisplaySumValue, 'DisplaySumCost': DisplaySumCost, 'DisplaySumSoldAmt': DisplaySumSoldAmt, } ) else: assert isinstance(self, HttpRequest) return render( self, 'app/index.html', { 'title':'Collector', 'year':datetime.now().year, } ) Template {% extends "app/layout.html" %} {% load humanize %} {% load l10n %} {% block content %} {% if request.user.is_authenticated %} <section style="border:1px solid black;background-color:lightyellow"> <h3 style="text-align:center"> Collection Summary for {{user.username}} </h3> <div class="row"> <div class="col-md-4"> <b>Total Cost: {{DisplaySumCost|localize}} </b> <b>Total Value: {{DisplaySumValue}} </b> <b>Total Sales: {{DisplaySumSoldAmt}} </b> </div> </div> </section> {% endif %} {% endblock %} -
Django and xhtml2pdf: UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte
I have a Django web application and I would like it to product an html pdf. I was sent HTML templates to work with, and out of the three I received, two work and one doesn't. Everytime I acsess this view, it gives me UnicodeDecodeError: 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte. Here is the full error: UnicodeDecodeError at /documents/973/generate/preliminary 'utf-8' codec can't decode byte 0xfe in position 0: invalid start byte The string that could not be encoded/decoded was: ��{% Here is my code: views.py def generatePreliminary(request, fileNumber): claim = ClaimMaster.objects.get(fileNumber=fileNumber) documents = [] for claimz in ClaimSub.objects.filter(claim=claim): docu = Document.objects.filter(claim=claimz) for doc in docu: documents.append(doc) data = { 'claim': claim, 'documents': documents, 'insurers': InsurerLink.objects.filter(claim=claim), 'insured': InsuredLink.objects.filter(claim=claim), } template = get_template('documentApplication/preliminaryreport.html') data_p = template.render(data) response = BytesIO() pdfPage = pisa.pisaDocument(BytesIO(data_p.encode("UTF-8")), response) if not pdfPage.err: return HttpResponse(response.getvalue(), content_type="application/pdf") else: return HttpResponse("Error") preliminary.html template: {% load static %} <html> <head> <style> <!-- /* Font Definitions */ @font-face { font-family: Wingdings; panose-1: 5 0 0 0 0 0 0 0 0 0; } @font-face { font-family: "Cambria Math"; panose-1: 2 4 5 3 5 4 6 3 2 4; } @font-face { font-family: Tahoma; panose-1: 2 11 … -
Get cleaned_data from queryset
Hi How can I get cleaned data from a queryset? And can I use .split() on an queryset? Ex. CartQuantity.objects.filter(customer=customer).values_list('cquantity', flat=True) The code above prints this: <bound method QuerySet.last of <QuerySet [4, 4, 4, 2, 4, 4, 5, 6, 5, 14, 10, 12]>> # need last number (12) But I only need the number 12 (the newest/latest number added to the model) I tried using .cleaned_data to only get the numbers (without <QuerySet etc.) and .split. I need the number 12 for a while loop. -
CS50W Project 1 WIKI - django paths capitalization problem in some entries
I have an issue with the implementation of Wiki I can't simply understand what's happening. My code so far for urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("<str:title>", views.entries, name="entries"), path("search/", views.search, name="search") ] and for views.py: from django.shortcuts import render from django.http import HttpResponse from django.urls import reverse from django.http import HttpResponseRedirect from markdown2 import Markdown from django import forms from . import util # render wiki's index def index(request): return render(request, "encyclopedia/index.html", { "entries": util.list_entries() }) # take path, remove capitalization and query for a matching entry def entries(request, title): nocase_title = title.lower() entry = util.get_entry(nocase_title) if entry: # convert markdown to html and render the entry route translator = Markdown() html = translator.convert(entry) return render(request, "encyclopedia/entry.html", {"entry":html, "title":nocase_title.upper()}) else: return render(request, "encyclopedia/not_found.html") def search(request): return render(request, "encyclopedia/search.html") My problem is this: In the url, I can't type a pass to wiki/python or wiki/css all in lowercase. Everytime I try it, I get 404 problem returned to me. I don't have issue with the other entries, I can type wiki/django, wiki/git or wiki/html.... But the most strange part is that I can type urls including those words in all caps … -
Django RF. how to get a Django Model with nested relationship
While testing my features in a Django Rest framework App, I need to get an object, let's call it Foo and this object has some nested relationships. I can get it by my making a request with the APIClient as such : class FooTest(TestCase): def setUp(self): self.client = APIClient() def test_foo_feature(self): foo_id = generator.generateFoo().id foo = self.client.get(reverse('foo-detail', args=[foo_id])).data I was wondering if I could call directly my FooSerializer in a certain way to get my Foo object with the nested relationships, instead of passing by the view with the help of the APIClient because simply calling Foo.objects.get(id=foo_id) doesn't return the nested relationships. -
Loading data faster from GraphQL endpoint for React
I have an e-commerce Django App that uses Graphene GraphQL to store some data at the backend. I use React at the frontend to load the data from the GraphQL endpoint. I have a requirement where I need to load all of the products (estimated to be about 100-170 products) in one go. This load is taking a long time at the moment (~7-10 seconds). Is there a way I can use caching to help the data load faster. I have read about this: https://docs.graphene-python.org/en/latest/execution/dataloader/ which seems like an option. Is there a better of doing this? Any help is appreciated -
Add a permission to Django admin panel without a model
I would like to create a custom user permission that is not related to a model that I can assign to users through the django admin panel. I have already tried something like class CustomPermissions(Permission): class Meta: proxy = True verbose_name = "MIDB Has write permission" permissions = ( ('can_write_to_midb', 'Can write to midb') ) admin.site.register(CustomPermissions) And variations on that. Is it possible to have just a user permission without a model that can be assigned through the admin panel? Thank you -
How do I match the model to the parent model, in html?
I have 2 pages, on the first page I create questions in the form, on the second page I want to display these questions and match the questions created on the first page, but I have to manually select the query result (I have 2 questions created). How do I do it dynamically? The question to fit its corresponding Answer model this is my code -> models.py from django.db import models from django.core.exceptions import ValidationError class Question(models.Model): question=models.CharField(max_length=100) answer_question=models.CharField(max_length=100, default=None) def __str__(self): return self.question class Answer(models.Model): questin=models.ForeignKey(Question, on_delete=models.CASCADE, related_name="questions") answer=models.CharField(max_length=100, null=True) def __str__(self): return str(self.questin) forms.py from django import forms from django.contrib.auth.models import User from django.core.exceptions import ValidationError from django.forms import ModelForm from .models import Question,Answer class QuestionForm(forms.ModelForm): class Meta: model=Question fields="__all__" class AnswerForm(forms.ModelForm): class Meta: model=Answer fields="__all__" views.py from django.shortcuts import render from django.shortcuts import render, HttpResponse from django.http import HttpResponseRedirect from django.shortcuts import redirect from .forms import QuestionForm,AnswerForm from .models import Question,Answer import random from django.forms import modelformset_factory def home(request): form=QuestionForm if request.method=='POST': form=QuestionForm(request.POST) if form.is_valid(): form.save() return render(request, "question/base.html", {"form":form}) def ans(request): questions=Question.objects.all() form=AnswerForm() if request.method=="POST": form=AnswerForm(request.POST) if form.is_valid(): print("Test validation only") print(request.POST) return render(request, "question/ans.html", {"form":form, "questions":questions}) ans.html <!DOCTYPE html> <html> <head> <title>question</title> </head> <body> <form …