Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to use django forms and models to save multiple checked data for the user?
Hey guys I am trying to develop a subscription based news aggregrator using django where user can login and subscribe to different news topics which appear in their dashboard based on their subscription. Can anybody help me with how to take multiple selected form data for topic selected by user and save it to the database for that user so that the specific subscription topics can also be retrieved later for dashboard news content ? ![Image link for form] [1]: https://i.stack.imgur.com/4o5J3.png -
How can I speed up batch creating of multiple related objects?
I use this for simplicity. Let say I have 2 models here A and B. I want to use A.objects.bulk_create(a_list) and B.objects.bulk_create(b_list) to batch create both A and B objects. But, B reply on A. So, I have to batch creating those objects in a for loop like this: for _ in some_list: a = A.objects.create(**kwargs) B.objects.create(a=a, **kwargs) The problem is that the speed is too slow and I wannt speed up. So, is there a workaround to speed up this? -
How to dynamically query and visualize postgis data using GeoDjango and Openlayers?
I am trying to implement dynamic query functionality in GeoDjango and OpenLayers. First, I filter the data and return it in GeoJSON format using Django serialize. Then, the return GeoJSON data visualize using OpenLayers 6. It works fine. But, When I try to filter data dynamically, it is not working. I don't understand the problem. Can anybody help me please? // GeoDjango Model from django.contrib.gis.db import models class Boundary(models.Model): division = models.CharField(max_length=50) district = models.CharField(max_length=50) upazila = models.CharField(max_length=50) union = models.CharField(max_length=50) geom = models.MultiPolygonField(srid=4326) def __str__(self): return self.division // views.py def boundary_data(request): """ bnd = Boundary.objects.filter(district="Khulna")""" // it is working fine name=request.GET.get("district") bnd = Boundary.objects.filter(district__iexact=name) // not working boundary = serialize('geojson', bnd) return HttpResponse(boundary, content_type='JSON') // urls.py from django.urls import path from . import views urlpatterns = [ path('boundary-data/', views.boundary_data, name="boundary-data"), path('bgd/', views.MapView.as_view(), name="bgd"), ] // query form <form method='GET' class="form-inline" action=""> <input class="form-control mr-sm-2" id="district" name="district" type="text" placeholder="Search"> <button class="btn btn-success" type="submit">Search</button> </form> //OpenLayers Code var style = new ol.style.Style({ fill: new ol.style.Fill({ color: 'gray', }), stroke: new ol.style.Stroke({ color: 'white', width: 1, }), text: new ol.style.Text() }); var map = new ol.Map({ target: 'map', layers: [ new ol.layer.Tile({ source: new ol.source.OSM() }), new ol.layer.Vector({ source: new ol.source.Vector({ format: … -
How can I fix my REST view to PATCH and serialize updates to an ArrayField() in my model?
I have a view that is used to update a field in my model. It's represented as follows: stock_list = ArrayField(models.CharField()) Each value in the ArrayField is separated by commas. I used a custom serializer method to allow for my backend to separate the elements in my PATCH obj by commas. serializers.py: class StringArrayField(ListField): """ String representation of an array field. """ def to_representation(self, obj): obj = super().to_representation(obj) # convert list to string return ",".join([str(element) for element in obj]) def to_internal_value(self, data): data = data.split(",") # convert string to list return super().to_internal_value(self, data) class StockListSerializer(serializers.ModelSerializer): stock_list = StringArrayField() class Meta: model = Bucket fields = ("stock_list",) Below is my view that I use, the URL's are linked up correctly, however I'm setting up my view wrong: view.py: class EditBucketSymbols(generics.RetrieveUpdateAPIView): permission_classes = [IsAuthenticated] serializer_class = StockListSerializer def get_queryset(self): return Bucket.objects.all() def get_object(self, queryset=None, **kwargs): item = self.kwargs.get('pk') return get_object_or_404(Bucket, pk=item) def patch(self, request, *args, **kwargs): item = BucketDetail.get_object(self) data = request.data item.stock_list = data.get("stock_list", item.stock_list) serializer = StockListSerializer(data=item.stock_list, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Here is the PATCH error I get: { "non_field_errors": [ "Invalid data. Expected a dictionary, but got str." ] } I'm not sure … -
Trying to create my first Django webpage but nothing loads when I run manage.py
I am following this tutorial: https://realpython.com/get-started-with-django-1/. I followed everything exactly the same but when I run manage.py, localhost:8000 only displays a blank webpage. I have a very simple HTML file that should display "Hello, World!" but it's not loading. Here is the code in settings.py: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello_world', views.py: from django.shortcuts import render # Create your views here. def hello_world(request): return render(request, 'hello_world.html', {}) My hello_world.html file: <!DOCTYPE HTML> <html lang="en"> <head> <meta charset="UTF-8"> <h1>Hello, World!</h1> </head> <body> </body> </html> The code in my project "personal_portfolio" personal_portfolio\urls.py: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('hello_world.urls')), ] And finally hello_world\urls.py: from django.urls import path from hello_world import views urlpatterns = { path('', views.hello_world, name = 'hello_world'), } I've made sure all the files are in the right place, but I can't figure out why localhost:8000 only displays a white page. When I run the hello_world.html file locally, it works just fine. Like this: local html file Any tips would be much appreciated. I'm frustrated I can't get this to work. -
Querying Models in Django Channels
I have been trying to query my database from my consumers.py but seems the query isn't working as I keep getting this error which shows that query wasn't sent. Here is the error : File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/generic/websocket.py", line 196, in websocket_receive await self.receive(text_data=message["text"]) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/Kitchen_Order/Order_app/consumers.py", line 52, in receive info = order_data_json['info'] KeyError: 'info' WebSocket DISCONNECT /ws/orders/ [127.0.0.1:53953] Here is my consumers.py set up: import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async def _get_order_info(self, number): return Order.objects.get(order_number = number) async def connect(self): self.groupname = 'kitchen' await self.channel_layer.group_add( self.groupname, self.channel_name, ) await self.accept() async def disconnect(self, code): await self.channel_layer.group_discard( self.groupname, self.channel_name, ) await super().disconnect(code) async def take_order(self, event): number = event['number'] details = event['details'] info = await self._get_order_info(number) await self.send(text_data=json.dumps({ 'number' : number, 'details' : details, 'info' : info, })) async def receive(self, text_data): order_data_json = json.loads(text_data) number = order_data_json['number'] details = order_data_json['details'] info = order_data_json['info'] await self.channel_layer.group_send( self.groupname, { 'type': 'take_order', 'number' : number, 'details' : details, 'info' : info, } ) Websocket code on the front end: document.querySelector('#submit').onclick = function(e) { const numberInputDom = document.querySelector('#id_order_number'); … -
Django: Adding multiple inline instances to a form
I want to have a button that allows the user to add another model instance to a parent model in a CreateView. In other words, I would like a button that works the same as the "Add another evidence" button in this screenshot of the admin page: My relevant views are: class EvidenceInline(InlineFormSet): model = Evidence factory_kwargs={ 'extra': 0, } form_class = NewClaimForm class ClaimCreateView(CreateWithInlinesView): model = Claim inlines = [EvidenceInline,] fields = ['claim_text', 'category'] template_name = 'bothsides/claim_form.html' def forms_valid(self, form, inlines): self.object = form.save() if 'add' in form.data: print(form.data['add']) return HttpResponseRedirect(self.get_success_url()) def get_context_data(self, **kwargs): context = super(CreateWithInlinesView, self).get_context_data(**kwargs) context['num_extra'] = self.model.num_evidence return context And my template is: {% load crispy_forms_tags %} <form method="POST" name="add-form"> {% csrf_token %} {{ form|crispy }} <div> {% for form in inlines %} {{ form|crispy }} {% endfor %} <input type="submit" value="Add Supporting Evidence" name="add"/> </div> </form> Incrementing the 'extra' property of EvidenceInline works except for it refreshes the page which I do not want. I am new to Django and understand that I may have made numerous mistakes here. Any help is appreciated. -
Django - How to automatically create a .docx file and save it to a model's FileField?
Here's my use case. I have a rental contract template (.docx file). I want to populate the fields of this contract by pulling data from my models and injecting them into the template (using Jinja tags), then save the output file directly to the database. So far so good. My problem is that I currently do this as a two step process; 1) open template, populate and save as new file; 2) upload the file as a FileField to my Model, thereby creating a duplicate... Is there a way for me to create and store the formatted file without first having to save it? (thus avoiding duplicates) According to this thread, the suggested approach is to use django.core.files.base.ContentFile and pass the content of the file as a string, like so. self.lease_draft.save("Name of the file", ContentFile("A string with the file content")) My problem is that ContentFile() only accepts strings or bytes as parameters. My input is a populated .docx file (DocxTemplate object), not a string. Any suggestions on how to approach this? Models.py class Booking(models.Model): lease_draft = models.FileField(upload_to='lease_drafts/', null=True) Views.py from django.core.files import File def populate_docx(self, template_path, context): draft_lease = DocxTemplate(template_path) /// Gets the template draft_lease.render(context) /// Populates the template self.lease_draft.save('Lease … -
Can you add a Browsable API into an ASP.NET application?
The Django web framework has a Browsable API and I would like to implement something similar in my ASP.NET (with ReactJS) application. Essentially, suppose that there's an API endpoint called api/test; I would like to be able to navigate to https://.../api/test in a web browser and be presented with a web page (React component) that contains what api/test normally returns but in a better, human-readable format like Django does. But when accessed as an API, it returns the content without the surrounding HTML page. The simple controller would look like: [ApiController] [Route("api/[controller]")] public class TestController : ControllerBase { [HttpGet] [Produces("text/json")] public IList<string> Get() { return new string[] { "hello", "world" }; } } It seems that something similar to Content Negotiation would work. So, I would either have to implement a custom formatter (which I'm not sure is the right approach) or make a middleware of my own. Does this sort of thing already exist somehow? Any suggestions on how to implement it if it doesn't already exist? Thanks in advance! -
how to display products from every seller and make it changing every time page reloading?
The default displaying in django is for the latest product first . how can I change the viewing way ? my view.py coding @login_required() def products(request): f = ForSaleProductFilter(request.GET, queryset=Product.objects.filter(status=ProductStatus.LISTED).order_by('-pub_date')) paginator = Paginator(f.qs, NB_PER_PAGE) page = request.GET.get('page') pproducts = paginator.get_page(page) request.session['products_filters'] = request.GET return render(request, 'products/products.html', {'filter': f, 'pproducts': pproducts}) sale = PorductSale() sale.product = product sale.buyer = buyer sale.seller = seller -
Django IntegrerField +1 by viewing page
I need to make object view counter, how i can make +1 to django models.IntegerField by viewing page with using of DetailView -
Typeerror in Django-Channels
I am trying to send data from client-side in my django app but I keep getting this error and the socket disconnects. I am lost to why this is so, This is the error: Exception inside application: receive() got an unexpected keyword argument 'text_data' Traceback (most recent call last): File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/routing.py", line 160, in __call__ send, File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/utils.py", line 51, in await_many_dispatch await dispatch(result) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/consumer.py", line 73, in dispatch await handler(message) File "/Users/MichaelAjanaku/Desktop/Kitchen-Order/order/lib/python3.6/site-packages/channels/generic/websocket.py", line 196, in websocket_receive await self.receive(text_data=message["text"]) TypeError: receive() got an unexpected keyword argument 'text_data' WebSocket DISCONNECT /ws/orders/ [127.0.0.1:49984] This is the consumers.py: import json from .models import Order from channels.db import database_sync_to_async from channels.generic.websocket import AsyncWebsocketConsumer class WSConsumer(AsyncWebsocketConsumer): @database_sync_to_async … -
Django rest framework do I need to close file before the response
I have an endpoint returning a FileResponse. When I use a code like the following I get an error 'read of closed file' The code looks like this: @action(detail=True, methods=['get'], url_path='download') def get_file(self, request, pk=None): instance = self.get_object() fa = getattr(instance, file_location) if fa: with open(fa.path, 'rb') as f: response = FileResponse(f, as_attachment=True) return response else: raise FileNotFound when I remove the with-block it works. Do I need the with block? -
How to display an avatar?
I made a function that generates avatars for users when they create a profile: users/models.py def random_image(): directory = os.path.join(settings.BASE_DIR, 'media') files = os.listdir(directory) images = [file for file in files if os.path.isfile(os.path.join(directory, file))] rand = choice(images) return rand class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar_new = models.ImageField (default=random_image) def __str__(self): return f'{self.user.username} Profile' For changing avatar i am using django-avatar There is a line like this (settings): DEFAULT_URL = ("avatar/img/default.jpg") I would like to display not a static image (default.jpg), but the result of the random function, which assigned the user an avatar. How can I make sure that the default url contains not a static image, but the result of the field avatar_new? Tried itDEFAULT_URL = Profile.avatar_new error. Need help pls -
GithubOauth gives "non_field_errors": [ "Incorrect value" ] after posting code to GithubLogin view
I am using GitHub OAuth to login to my django_RESTFRAMEWORK api. with front end React js. Oauth works fine when i try to login with my github account. but gives "non_field_errors": [ "Incorrect value" ] i am very certain that code is correct. and the fact this works for my github account. please help http://localhost:8000/accounts/dj-rest-auth/github/?code=***************** -
Adding Websockets to Django server deployed on Azure Appservice
I have a Django application which starts a server using the websockets https://websockets.readthedocs.io/en/stable/index.html library for Python. The manage.py file looks like this: import os import sys import asyncio import threading if __name__ == '__main__': os.environ.setdefault( 'DJANGO_SETTINGS_MODULE', 'UPH_Chart_Re.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc try: from WebsocketClass import StartServer x = threading.Thread(group=None, target=StartServer, name="Websocket Thread") x.daemon=True x.start() except ImportError as exce: raise ImportError("Importing WebsocketsClass failed") from exce execute_from_command_line(sys.argv) The StartServer function starts a websocket server using asyncio: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) start_server = websockets.serve(Receive, "localhost", 5001) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever() The Django webpages and websocket server work perfectly on my local machine. The problem I'm running into now is that when deploying to Azure Web App Service, I don't seem to be able to access the sockets. My Web App Service has Websockets set to enabled, and I get no errors on my deployment. However, I can't seem to connect to the websocket at all. I have tried setting the port to 443, which is considered a forbidden port since … -
Django and chartjs using json (doesn't show chart)
I'm trying to display a chart in Django with data from database using JSON. When I go to /distancechart I see my data printed. But when it comes to chart I get blank screen, nothing shows. I was using some tutorials from internet and I have no idea what is wrong here... views.py fragment def distancechart(request): labels = [] data = [] queryset = Distance.objects.values('day', 'distance') for entry in queryset: labels.append(entry['day']) data.append(entry['distance']) return JsonResponse(data={ 'labels': labels, 'data': data, }) distance.html {% extends 'index.html' %} {% block content %} <canvas id="distancechart" width="1000" height="400"></canvas> <script> $.get('{% url "distancechart" %}', function(data) { var ctx = $("#distancechart").get(0).getContext("2d"); new Chart(ctx, { type: 'bar', data: { labels: data.labels, datasets: [{ label: 'Distance', data: data.data, backgroundColor: [ 'rgba(255, 99, 132, 0.2)', 'rgba(54, 162, 235, 0.2)', 'rgba(255, 206, 86, 0.2)', 'rgba(75, 192, 192, 0.2)', 'rgba(153, 102, 255, 0.2)', 'rgba(255, 159, 64, 0.2)' ], borderColor: [ 'rgba(255, 99, 132, 1)', 'rgba(54, 162, 235, 1)', 'rgba(255, 206, 86, 1)', 'rgba(75, 192, 192, 1)', 'rgba(153, 102, 255, 1)', 'rgba(255, 159, 64, 1)' ], borderWidth: 1 }] }, options: { scales: { yAxes: [{ ticks: { beginAtZero: true } }] } } }); }); </script> {% endblock %} -
Django checkbox form does not update
I have form where I want to let users add their skills by using check boxes. I can get the check boxes to render in the template but I can't get it to update if the user select a check box, nor am I able to let it show current active skill. I am a bit confused what's wrong, any ideas? My models.py file class Skills(models.Model): math = models.BooleanField(default=None) language = models.BooleanField(default=None) driving = models.BooleanField(default=None) account = models.ForeignKey( Account, on_delete=models.CASCADE, default=None, null=False ) My forms.py file class SkillsForm(forms.ModelForm): SKILLS = ( (True, 'math'), (True, 'language'), (True, 'driving'), ) skills = forms.MultipleChoiceField(choices=SKILLS, widget=forms.CheckboxSelectMultiple) def clean_skills(self): print(self.cleaned_data["skills"], self.cleaned_data["skills"][0]) return self.cleaned_data["skills"][0] class Meta: model = Skills fields = ( 'math', 'language', 'driving', ) My views.py file @login_required def userSkills(request): if request.user.is_authenticated: if request.method == "POST": skills = SkillsForm(request.POST, instance=request.user) if skills.is_valid(): skills.save() return HttpResponseRedirect(request.path_info) else: skills = SkillsForm(instance=request.user) return render(request, 'page/userprofile.html', { "skills": skills, }) My template file <ul class="list-group"> <form method="POST" action=""> {% csrf_token %} <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>math</label> {{ skills.math }} </div> </li> <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>language</label> {{ skills.language }} </div> </li> <li class="list-group-item"> <div class="custom-control custom-checkbox"> <label>driving</label> {{ skills.driving }} </div> </li> <input class="btn btn-primary" type="submit" … -
Django Inheritance one model choice field from another
I have couple tables in DB. class VehicleBrand(models.Model): name = models.CharField(max_length=128, unique=True) class VehicleModel(models.Model): name = models.CharField(max_length=128, unique=True) class Vehicle(models.Model): link = models.CharField(max_length=256, unique=True, blank=False, null=False) model = models.ForeignKey(VehicleModel, on_delete=models.PROTECT) brand = models.ForeignKey(VehicleBrand, on_delete=models.PROTECT) I tried to crate form with two ModelChoiceField depending one from another. I have first Field (just all items from VehicleBrand) # first field brand = forms.ModelChoiceField(queryset=VehicleBrand.objects.all()) Next I want to get qs of models depending of first choice: # get brand brand = VehicleBrand.oblects.get(name=brand) # get qs for all items with chosen brand qs = Vehicle.objects.filter(brand=brand) # I want get second field with choices as list of distinct models values model = qs.values('model').distinct() For example I have next table 1 link1 Toyota Corolla 2 link2 Toyota Camry 3 link3 Nissan Altima 4 link4 Nissan Almera If I choose 'Toyota' I wanna have only models for it: 'Corolla' and 'Camry'. I wanna get it in one page dinamically depending of first(brand) field. Is it possible? Could someone give me advise please? Thanks. -
How to to create a Dynamic variable and Value in Django Admin
Please, I am completely new to this approach but I believed it is possible. I want to dynamically create something like this image in Django admin and render the result for other users to see. -
Manytomany into notifications does not work
I don't really understand why when I save my model. The notification does not save the ManyToMany relationship, exemple. Do you have any idea? def notifs_rerservationorder(sender, instance, *args, **kwargs): rerservationorder = instance table_nb = rerservationorder.exemple.all() notify = Notification(rerservationorder=rerservationorder, notification_type=9) notify.save() notify.exemple.add(*table_nb) notify.save() post_save.connect(notifs_rerservationorder, sender=RerservationOrder class Notification(models.Model): NOTIFICATION_TYPES = ... ... exemple = models.ManyToManyField('post.Exemple',blank=True, null=True, related_name='notifs_exemple') ... ) -
Python Flask-WTF Forms not showing up when running server, only base html not child html file, how can i fix it?
tried to create a signup form, here is my file tree right now: -mysite\ --app.py --forms.py --form.html --templates\ ----index.html so im pretty sure the structure is fine, however when i use terminal in PyCharm and run command, flask run, server starts without errors, however my forms.py is not running just index.html here is what my scripts look like from forms import RegistrationForm app = Flask(__name__, instance_relative_config=False) app.testing = True app.config['SECRET_KEY'] = 'any secret string' @app.route('/', methods=('GET', 'POST')) def registration(): form = RegistrationForm() if form.validate_on_submit(): return redirect(url_for('success')) return render_template( 'index.html', form=form ) so when i click on the link in the terminal from pycharm i get index.html boots up, however, the script from form.html does not work.. i have in form.html: {% extends 'index.html' %} ........... {% endblock %} obviously i have some script between the blocks .. not too sure what i am doin wrong. parent html = index.html child html = form.html -
Items after reload showing in different order Django
Hi I've made django webstore and there is small yet annoying bug. If I add click on add quantity in my cart items after reload are in different order note this only happens when user is not authenticated here are short gifs to help you understand my probelm not working correctly when user is auth and working correctly on guest user cart.js var updateBtn =document.getElementsByClassName("update-cart") for (i = 0; i < updateBtn.length; i++){ updateBtn[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action if (user === "AnonymousUser"){ addCookieItem(productId,action) }else{ updateUserOrder(productId, action) } }) } function addCookieItem(productId,action){ if(action == "add"){ if(cart[productId] === undefined){ cart[productId] = {'quantity':1} }else{ cart[productId]['quantity'] += 1 } } if (action == "remove" || action =="delete"){ cart[productId]['quantity'] -= 1 if(cart[productId]['quantity'] <= 0){ delete cart[productId] } } document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/" history.go(0) } function updateUserOrder(productId, action){ var url = 'http://127.0.0.1:8000/updateItem' 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) history.go(0) }) } html <div class="row no-gutters"> <div class="col-4"> <div class="controlQtyCart"> <i data-product="{{ x.product.id }}" data-action="remove" class="fas fa-minus update-cart updatePointer"></i> </div> </div> <div class="col-4"> <div class="controlQtyCart"> &nbsp;{{x.quantity}} </div> </div> <div class="col-4"> <div class="controlQtyCart"> <i data-product="{{ x.product.id }}" … -
Django: Parent object has no attribute children_set
I have these two models: class Periodo(models.Model): # id usato per identificare i documenti # periodo rilevato in fattura data_i_p = models.DateField('data inizio', blank=True) data_f_p = models.DateField('data fine ', blank=True) mc_p = models.DecimalField('mc', max_digits=7, decimal_places=0, blank=True, default=0) idfatt = models.ForeignKey(FattAqp, verbose_name="fattura AQP", on_delete=models.CASCADE, related_name='periodo_rel') descr = models.CharField('descrizione', max_length=50) objects = models.Manager() class Meta: verbose_name = 'Periodo' class DettFAqp(models.Model): imponibile = models.DecimalField('imponibile', max_digits=8, decimal_places=2, default=0) iva = models.DecimalField('%IVA', max_digits=4, decimal_places=2, default=10) mc = models.DecimalField('qtà (gg/mc)', max_digits=7, decimal_places=0, blank=True, default=0) voce = models.ForeignKey(VoceAqp, verbose_name="metodo di ripart.", on_delete=models.CASCADE) periodo = models.ForeignKey(Periodo, verbose_name="Periodo in fattura", on_delete=models.CASCADE, related_name='dettfaqp', help_text=u"periodo cui la voce appartiene") rigo = models.DecimalField('rigo', max_digits=2, decimal_places=0, default=0, help_text=u"rigo di fattura") when I try to access the set related to the parent I get the following error: >>> p=Periodo.objects.get(pk=2) >>> p <Periodo: consumo accertato in 344 gg> >>> p.dettfaqp_set.all() Traceback (most recent call last): File "<input>", line 1, in <module> p.dettfaqp_set.all() AttributeError: 'Periodo' object has no attribute 'dettfaqp_set' Any suggestion? Many tankds in advance. -
Nextcloud as User Master for other web apps (i.e. django based)
I have a Nextcloud instance where all potential users have an account. I would like to set up an Open Source Doodle (Bitpoll) that is django based, as I don't like the nextcloud poll app. For security reasons I would like to limit the Doodle app to users of my nextcloud. Also I don't want them to enter a password using the doodle app (so single sign on is required). I imagine a similar user user flow as the Login in with Github button that can be used to also create user accounts. The doodle app supports LDAP, so does nextcloud. There are django modules for OAuth as well as for the nextcloud. I have no LDAP experience at all and only very little OAuth experience. With which Nextcloud Settings / Apps and which Django Apps (and an idea of the settings) can I realize the explained scenario? To be more precise: Do I need to use LDAP at all? Or can I configure OAuth in a way that all users that come from nextcloud.mydomain.org generate a new account in the app? What are the correct OAuth terms for my nextcloud istance and for the doodle app in this scenario? …