Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What JSESSIONID cookie when connecting to Spotfire server?
I am embedding a Spotfire visualization into my Django webpage. I am using the following JS API: https://community.tibco.com/wiki/spotfire-tipstricks-embed-spotfire-visualizations-webpages The API works well except that it gives me a cookie error like the following: How can I solve this? -
Cors Headers error Django 1.11 accessing data from different port
I have upgraded my python version from 3.4 to 3.8 after doing that upgradation I am getting cors headers error Access to XMLHttpRequest at '10.31.101.66:8081/administration/UserLogin/' from origin '10.31.101.66:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource this error occurs when one port try's to access data from the second port. -
How do I insert a parser into a django structure?
I am writing a website on the Django framework. Created a standard Django structure, changed SQLite to PostgreSQL. I wrote a parser in a separate .py file. Then I sketched out the structure for the database. The problem is that I don't know where to insert the code with the parser. I will need, for example, that the parser is loaded once a day, updating my database. There is an idea to insert a parser into the models.py but, but I do not know how to work correctly. -
Launching celery worker creates too many connexions to redis
I'm using celery with redis as a broker in a django project. The problem I have is that even with no task running, just launching the worker produces up to 10 new connexions to redis server. celery -A proj worker -l INFO If I check CLIENT LIST in redis-cli I see this: 127.0.0.1:6379> CLIENT LIST id=272 addr=127.0.0.1:48846 fd=16 name= age=63 idle=63 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r cmd=sadd user=default id=270 addr=127.0.0.1:48842 fd=14 name= age=64 idle=64 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r cmd=publish user=default id=4 addr=127.0.0.1:46946 fd=8 name= age=14901 idle=0 flags=N db=0 sub=0 psub=0 multi=-1 qbuf=26 qbuf-free=32742 argv-mem=10 obl=0 oll=0 omem=0 tot-mem=61466 events=r cmd=client user=default id=265 addr=127.0.0.1:48832 fd=9 name= age=64 idle=0 flags=b db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20536 events=r cmd=brpop user=default id=266 addr=127.0.0.1:48834 fd=10 name= age=64 idle=63 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r cmd=sadd user=default id=273 addr=127.0.0.1:48848 fd=17 name= age=63 idle=2 flags=P db=2 sub=0 psub=1 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20504 events=r cmd=psubscribe user=default id=274 addr=127.0.0.1:48850 fd=18 name= age=63 idle=63 flags=N db=2 sub=0 psub=0 multi=-1 qbuf=0 qbuf-free=0 argv-mem=0 obl=0 oll=0 omem=0 tot-mem=20520 events=r … -
table only shows the first page in Django pagination
I have developed a web app using Django. I have created a table pagination. But only the first view of the table shows(no pagination created). Where is my error? view.py def Browse_and_adopt(request): Title_list = Title.objects.all() page = request.GET.get('page', 1) paginator = Paginator(Title_list, 10) try: Titles = paginator.page(page) except PageNotAnInteger: Titles = paginator.page(1) except EmptyPage: Titles = paginator.page(paginator.num_pages) return render(request, 'bms/inbox/Browse_and_adopt.html', {'Titles': Titles}) Browse_and_adopt.html <table id="myTable"> <thead> <tr> <th>Title</th> </tr> </thead> <tbody> {% for book in Titles %} <tr> <td>{{ book.title }}</td> </tr> {% endfor %} </tbody> </table> <script> $(document).ready(function() { $(".dataTables_filter input").attr("placeholder", "By title, "); var table = $('#myTable').DataTable(); $('#myTable tbody').on('click', 'tr', function () { if ($(this).hasClass('selected')) { $(this).removeClass('selected'); } else { table.$('tr.selected').removeClass('selected'); $(this).addClass('selected'); } }); }); </script> -
Why is it returning 204 instead of 403? Custom permissions does not working
I have a table that stores parent - child records. Today, I noticed a problem while writing a unit test. Even if the requester is not the parent of the child, they can delete the record. But on the view side, if the user is not the owner of the record, the delete button is not active. So it works in the view side. If I make the request using postman, the record is deleted regardless of who owns it. How can I check that whether the user is the owner of the record? I am following an example project and the creator of that project has done a similar permission. Child List Model class ChildList(models.Model): parent = models.ForeignKey( "account.ParentProfile", on_delete=models.CASCADE, related_name="parent_children", verbose_name=AccountStrings.ChildListString.parent_verbose_name) child = models.OneToOneField( "account.ChildProfile", on_delete=models.CASCADE, related_name="child_list", verbose_name=AccountStrings.ChildListString.child_verbose_name) def __str__(self): return f"{self.parent.user.first_name} {self.parent.user.last_name} - {self.child.user.first_name} {self.child.user.last_name}" class Meta: verbose_name = AccountStrings.ChildListString.meta_verbose_name verbose_name_plural = AccountStrings.ChildListString.meta_verbose_name_plural Child List Destroy View class ChildListItemDestroyAPIView(RetrieveDestroyAPIView): """ Returns a destroy view by child id value. """ queryset = ChildList.objects.all() serializer_class = ChildListSerializer permission_classes = [IsAuthenticated, IsParent, IsOwnChild] def get_object(self): queryset = self.get_queryset() obj = get_object_or_404(ChildList,child = self.kwargs["child_id"]) return obj Permission class IsOwnChild(BasePermission): """ To edit or destroy a child list record, the user must … -
How to solve python model to called by a web using django
i'm a beginner for python django, and i try to input my model (the model that i've train at google collab using CNN) for classification of Braille, but when i test the model, there is error like [no such file or directory ][1] can you solve this? am i wrong with the code? [1]: https://i.stack.imgur.com/Bo077.jpg this is the code : def prosesImg(request): filelink = request.POST.dict().get("myfiles") tf.compat.v1.disable_eager_execution() img_height, img_width=224,224 model_graph = tf.Graph() with model_graph.as_default(): tf_session=tf.compat.v1.Session() with tf_session.as_default(): models=load_model('./model/BrailleNet.h5') testimage='.'+filelink img = image.load_img(testimage, target_size=(img_height, img_width)) x = image.img_to_array(img) x = x / 255 x = x.reshape(1, img_height, img_width, 3) with model_graph.as_default(): with tf_session.as_default(): predi = models.predict(x) if np.argmax(predi) == 0: predictedLabel = """Classification : huruf A <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf B <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf C <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf D <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf E <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf F <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf G <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : huruf H <br/>""" elif np.argmax(predi) == 1: predictedLabel = """Classification : … -
How to create unlimited number of headings for the template
''' class blogpost(models.Model): created_by=models.ForeignKey(User,on_delete=models.CASCADE) topic=models.CharField(max_length=122,null=False) title=models.TextField(blank=False) slug=models.SlugField(max_length=250,null=True) post=models.TextField() #more other headings and their text which can only be added from admin pannel heading1=models.CharField(max_length=250,blank=True) post1=models.TextField(blank=True) heading2=models.CharField(max_length=250,blank=True) post2=models.TextField(blank=True) heading3=models.CharField(max_length=250,blank=True) post3=models.TextField(blank=True) likes=models.ManyToManyField(User, related_name='blog_posts',blank=True) date=models.DateTimeField(auto_now_add=True ) ''' Above i have created different fields for every heading to print on the template but if i want to store unlimited or unknwon number of headings and their associated text then what can i do??? <div> <p class='fs-5 fw-light'>{{data.post | linebreaks}}</p> </div> <div> <h4>{{data.heading1}}</h4> <p class='fs-5 fw-light' > {{data.post1 | linebreaks}}</p> </div> <div> <h4>{{data.heading2}}</h4> <p class='fs-5 fw-light' > {{data.post2 | linebreaks}}</p> </div> <div> <h4>{{data.heading3}}</h4> <p class='fs-5 fw-light'> {{data.post3 | linebreaks}}</p> </div> -
Saleor-Storefront has error:Redis adress already in use
Hi everyone i have a problem with redis when i call migration: sudo docker-compose run --rm api python3 manage.py migrate I tried to stop, disable, shutdown redis, close ports etc. but nothing seemed to work. Can anyone help me? I am desperate My error screen: Starting saleor-platform_jaeger_1 ... done Starting saleor-platform_db_1 ... done Starting saleor-platform_redis_1 ... Starting saleor-platform_redis_1 ... error ERROR: for saleor-platform_redis_1 Cannot start service redis: driver failed programming external connectivity on endpoint saleor-platform _redis_1 (af785cb919fe2290aeedfc681fe4a39767b94b59856b1ed779f5 9587ef354401): Error starting userland proxy: listen tcp 0.0.0.0:6379: bind : address already in use ERROR: for redis Cannot start service redis: driver failed programming external connectivity on endpoint saleor-platform_redis_1 (af785cb919 fe2290aeedfc681fe4a39767b94b59856b1ed779f59587ef354401): Error starting userland proxy: listen tcp 0.0.0.0:6379: bind: address already in use ERROR: Encountered errors while bringing up the project. I tried all of these commands and migrated again: sudo service redis stop sudo update-rc.d redis_6379 defaults sudo /etc/init.d/redis-server stop redis-cli shutdown redis-cli shutdown nosave sudo killall redis-server sudo killall redis-cli sudo kill -9 `sudo lsof -t -i:6379` sudo kill -9 $(sudo lsof -t -i:6379) None of them worked though. I think my 6379 port is still open but i cannot close it -
Python manage.py Identified 0 errors but unable to runserver
I have not been able to run my server even with 0 errors, it shows me this: Performing system checks... System check identified no issues (0 silenced). Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x0000028159B61048> Traceback (most recent call last): File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\commands\runserver.py", line 123, in inner_run self.check_migrations() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\core\management\base.py", line 427, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 268, in build_graph raise exc File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\loader.py", line 242, in build_graph self.graph.validate_consistency() File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in validate_consistency [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 243, in <listcomp> [n.raise_error() for n in self.node_map.values() if isinstance(n, DummyNode)] File "C:\Users\user\AppData\Roaming\Python\Python37\site-packages\django\db\migrations\graph.py", line 96, in raise_error raise NodeNotFoundError(self.error_message, self.key, origin=self.origin) django.db.migrations.exceptions.NodeNotFoundError: Migration admin.0004_auto_20190704_0341 dependencies reference nonexistent parent node ('admin', '0003_logentry_add_action_flag_choices') -
If/when statement in django models to create another model field
I'm trying to create a model field that is a result of another model field. I am unable to articulate this properly, but I will try anyway. I have employees who include everyone in the office, then I have a role for them too. All the staff are Engineers, and a few of the Engineers are also Managers. so when creating an Employee, I have to select if they are just an Engineer or a Manager. if the role is a Manager, then I want to create a model field as manager = models.Charfield(???????????) from django.db import models class Roles(models.Model): role = models.CharField(max_length=22) def __str__(self): return self.role class Engineers(models.Model): region = ( ('SS', 'South-South'), ('SW', 'South-West'), ('SE', 'South-East'), ('NE', 'North-East'), ('NW', 'North-West'), ('NC', 'North-Central'), ) firstname = models.CharField(max_length=20) lastname = models.CharField(max_length=20) email = models.EmailField(max_length=50) username = models.CharField(max_length=20, unique=True) phone = models.CharField(max_length=11) position = models.ForeignKey(Roles, on_delete=models.DO_NOTHING, max_length=20) workarea = models.CharField(max_length=20, choices=region) manager = models.(if role selected = Manager), then the Employee name should be here def __str__(self): return self.firstname + ' ' + self.lastname I'd appreciate any help or redirection to any resources that can help, or any different way of doing this. -
How to get Image uploads in HTML to be of ratio 1:1
I am using the Django framework to allow drivers to register with my site, and one of the fields that they need to submit is a picture of themselves. A snippet of code from forms.py... your_picture = forms.ImageField(help_text="A picture of yourself so that we know who you are") I want to make sure always that the user inputs an image that is 1:1. Especially when it comes to mobile devices and the user selects an already available picture, I need it to allow the user to crop it as a 1:1, like how I have seen in many different applications. I want to know how I can do a client-side check and a server-side validation to see if the image meets my requirements. Just for your information, the images are stored and uploaded into AWS S3. Any support would be greatly appreciated thanks! -
django - Restrict "n" or More Characters Present in a Previous Password
I am using django for password management and I understand that DJango uses one-way hash to store passwords. My application is using django.contrib.auth.hashers.PBKDF2PasswordHasher I have a table PasswordHistory where I save last 10 passwords. Passwords are saved using django hashing. I want to restrict user to have a password with "n" or more characters present in a previous password. Right now, it is not possible as I can not get password from hashed string. Is there a way to do so using django? Otherwise, I will have to save passwords using my own encryption/decryption logic. I know this is not a secure way, but may be the last option I have. -
Django, store Post object with image in post field of other object
I have a problem in django and I don´t know how to solve it. I have a class named "Post", including an image, a recipe and a caption. After that, I just want to store the Post-object in the field "posts" of my Client-class. But it is not working, I get the error Object of type AddForm is not JSON serializable. Probably the error is in my models.py, but I can´t figure out where. I appreciate any help, and thanks in advance. forms.py class AddForm(forms.ModelForm): image = forms.FileField() caption = forms.TextInput() recipe = forms.TextInput() class Meta: model = Post fields = ["image", "recipe", "caption"] models.py def default_posts(): return {"posts": []} class Client(models.Model): posts = models.JSONField(default=default_posts) class Post(models.Model): client = models.ForeignKey(Client, on_delete=models.CASCADE, null=True, blank=True) image = models.ImageField(upload_to="images/") caption = models.TextField(default=None) recipe = models.TextField(default=None) views.py @login_required(login_url="login") def add(response): if response.method == "POST": form = AddForm(response.POST, response.FILES) if form.is_valid(): form.save() current_user = Client.objects.get(id=response.user.id) current_user.posts["posts"].append(form) current_user.save() return redirect("home") else: form = AddForm() return render(response, "main/add.html", {"form":form}) -
Retrieve set of data only with one query | Django
I have a following question. For example I have a Django model with 2 field ( it is not a real model but carries in itself same conception, all other fields are omitted for a sake of simplicity): class Foo(models.Model): id = models.UUIDField() created = models.DateTimeField(auto_now_add=True) Lets say we have 1000 entries of this model in database and we have an UUID in input data that might or might not belong to one of these 1000 entries ( id field) Goal is like this: Get following data with maximum of 1 query to database without retrieving whole set of data from database as well Whether or not one of these 1000 entries has this UUID as id field? If so, we need created field of this exact entry Whether or not there are at least 100 entries in database that have created field earlier then this exact entry ( where id == UUID) Django 3.2 Thanks -
how do i import / export social accounts using django import export package?
I successfully imported and exported other data but not able to import/export social accounts and social application tokens. I am using django allauth for social account creation. There is no other way to login in. -
Optomizing Django API Queries to reduce database hits
This is just on my belief that Django has unlimited possibilities. I have an API, testing it with debug-toolbar, I have up to 13 hits per request. I would like to think there is something I can do to bring down the database hits to 1. Here is my API List View: class ProductsListAPIView(ListAPIView): queryset = Product.objects.active() serializer_class = ProductSerializer filter_backends = [SearchFilter, OrderingFilter] permission_classes = [HasAPIKey | AllowAny] search_fields = ['product_title', 'product_description', 'user__first_name', 'product_type', 'product_price', 'product_city'] pagination_class = ProductPageNumberPagination def get_serializer_context(self, *args, **kwargs): context = super(ProductsListAPIView, self).get_serializer_context(*args, **kwargs) context['request'] = self.request coordinates = self.request.GET.get("coordinates") if not coordinates or len(coordinates) <= 4: coordinates = '0.0,0.0' context['coordinates'] = coordinates return context def get_queryset(self, *args, **kwargs): query = self.request.GET.get("search") lookups = () if query and len(query) > 0: queryArray = query.split() for q in queryArray: lookups = (Q(product_title__icontains=q) | Q(product_description__icontains=q) | Q(product_type__icontains=q) | Q(product_city__icontains=q) | Q(user__first_name__icontains=q) | Q(user__last_name__icontains=q) | Q(product_address__icontains=query) ) # If user is loggedIn and discovery range / point and address is set # Returns products just in that range. uid = self.request.GET.get("uid") queryset_list = self.queryset if uid and len(uid) > 5: try: user = CustomUser.objects.get(uid=uid) from django.contrib.gis.measure import D if user is not None and user.point is not None … -
How can you group a list extracted from queryset many-to-many field?
I have a model that describes the essence of a TV channel: class ChannelCategory(models.Model): name = models.CharField(max_length=200, db_index=True) def __str__(self): return '%s' % self.name class Channel(models.Model): category = models.ForeignKey(ChannelCategory, on_delete=models.CASCADE) name = models.CharField(max_length=200, db_index=True) class Meta: ordering = ['category'] def __str__(self): return '%s: %s' % (self.category, self.name) I also have a model that describes the essence of the tariff. Channels are linked to a tariff using a relationship many-to-many. class Tariff(models.Model): channels_list = models.ManyToManyField(Channel, blank=True, db_index=True, symmetrical=False) def __str__(self): return '%s' % self.name If I call the tariff object, I can get a list of channels that are assigned to it: queryset = Tariff.objects.prefetch_related('channels_list') for tariff in queryset: channels_list = [tariff.channels_list.all()] print (channels_list) And get the next set: <QuerySet [<Channel: channelcategory1: channel1>, <Channel: channelcategory1: channel2>, <Channel: channelcategory2: channel3>]> I want to receive queryset the following form: <QuerySet [<Channel: channelcategory1: channel1, channel2>, <Channel: channelcategory2: channel3>]> How can I do that? -
Django Postgres Search
I may be misunderstanding something after reading the docs but I am confused as to why my search function isn't quite working. The code is as follows: def product_search(request): form = ProductSearchForm() q = '' results = [] if 'q' in request.GET: form = ProductSearchForm(request.GET) if form.is_valid(): q = form.cleaned_data['q'] vector = SearchVector('name', weight='A') + \ SearchVector('artist', weight='B') query = SearchQuery(q) results = Product.objects.annotate(rank=SearchRank(vector, query, cover_density=True)).order_by('-rank') results = Product.objects.annotate(search=SearchVector('name', 'artist')).filter(search=SearchQuery(q)) return render(request, 'my_site/search.html',{ 'q': q, 'results': results }) As far as my understanding is SearchVector() should allow the searching of multiple fields. If I search just for product names it works fine, but if I search for an artist name it returns no results, even if I type the full direct name, and I am not understanding why. Any help would be greatly appreciated! I will also post my product model just in case that may be of some use. model: class Product(models.Model): name = models.CharField(max_length=120) shortened_name = models.CharField(max_length=50) date_of_creation = models.CharField(max_length=20, null=True) history = models.CharField(max_length=255) price = models.DecimalField(max_digits=9, decimal_places=2) discount_price = models.FloatField(blank=True, null=True) style = models.CharField(max_length=50) artist = models.ForeignKey(Artist, on_delete=models.SET_NULL, null=True) image = models.ImageField(upload_to='images', null=True) slug = models.SlugField() def __str__(self): return self.name def get_absolute_url(self): return reverse('product', args=[self.slug]) def save(self, … -
How to get child objects on condition in Django
I`m trying to fetch data from the parents' model to the child model who fulfills the condition. I have a product model and there is also a product review model. so I need to fetch records from a product model to reviews models that have a rating of 1. class Product(models.Model): name = models.CharField(max_length=250) code = models.IntegerField(unique=True) ... class Review(models.Model): name = models.CharField(max_length=250) rating = models.IntegerField(default=1) message = models.TextField(max_length=2000) ... output:- from all product models get reviews who have a rating of 1. like this MySQL query SELECT * FROM product_product as product INNER JOIN product_productreviews as review ON product.id = review.product_id WHERE review.rating = 1.0 -
Django : Aggregate Functions on nested query many-to-many relationship
My model.py is class Place(models.Model): id = models.IntegerField(primary_key=True) location = models.CharField(max_length=100) class Meta: db_table = 'place' managed=False class Session(models.Model): id = models.IntegerField(primary_key=True) place = models.ForeignKey(Place,related_name='session',on_delete=models.CASCADE, null=True) start = models.DateField(auto_now=True) counts = models.IntegerField() class Meta: db_table = 'session' managed=False class Animal(models.Model): id = models.IntegerField(primary_key=True) sess = models.ForeignKey(Session,related_name='details',on_delete=models.CASCADE, null=True) type = models.CharField(max_length=100) is_active = models.BooleanField() length = models.DecimalField(max_digits=6, decimal_places=2) class Meta: db_table = 'animal' managed=False I need to get a summary table, with min, max, standard_deviation, average and count of animals in the particular location based on selection of particular day, week, month or year. I tried using aggreagate and annotations, but the result was not as expected. Please suggest me how can this be achieved? The output I am trying to get is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", "count": 600, "details": [ { "id": 1, "length_max": "22.00", "length_min": "10.00", "length_avg": "16.43", "length_std": "16.00", "is_active": false, "type": "dog" } ] }, { "start": "2021-01-02", "count": 400, "details": [ { "id": 2, "length_max": "19.00", "length_min": "12.00", "length_avg": "15.00", "length_std": "13.00", "is_active": true, "type": "dog" } ] }, ] } ] But the output that I am getting is [ { "location": "Loc 1", "session": [ { "start": "2021-01-01", … -
Can I use admin-stylle inlines in my templates?
Is it possible to use admin-style inlines to list the related model instances in a template? For example, if I have a poll and questions... class Poll(models.Model): title = models.CharField(max_length=100) # ... class Question(models.Model): poll = models.ForeignKey(Poll, on_delete=models.CASCADE, related_name="questions") In the admin, I'd create an inline for the questions and add it to the ModelAdmin. But can I use something similar in the template? Once again, it would be used to list the instances, not to edit them. -
Embedding Spotfire into Django
I am building a website using Django, currently hosted in my local machine. I want to embed Spotfire into my Django website. I use a corporate Spotfire server which is hosted in the corporate intranet network. I am already logged in to the network using Windows authentication. I tried embedding Spotfire into an Html webpage. I tried two ways: 1. Using the JavaScript API: https://community.tibco.com/wiki/spotfire-tipstricks-embed-spotfire-visualizations-webpages The issue I found here is that it shows a blank page. I searched the problem and it seems it is because of SameSite error: The error is further explained here: https://support.tibco.com/s/article/Tibco-Spotfire-JavaScript-Mashup-API-stops-working-in-Chrome-due-to-SameSite-problem?_ga=2.207502931.1596109997.1627212003-1100468487.1624779216 I am new to Django, so I couldn't find a solution to set the SameSite cookie in Django to 'None'. 2. Using iframe: https://youtu.be/dY4_aYd5uZM The iframe solution does display a Spotfire window inside the webpage but it requires login, and when I click login, nothing happens and it gives out the same issue as above (SameSite error). I hope you could help me solve the issue or suggest me a new workaround. -
django save table rows data to database using for loop
I'm new in Django python ,i have a table with some rows which filled with javascript, I have a problem, when click Save button , I want get table rows count and store all rows data to database, and go to specific page; thank you; ''' <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form id="myform1" name="myform1" action="{% url 'order' %}" method="POST" onsubmit="return validForm()"> {% csrf_token %} <fieldset class="field2"> <div id = "dv3" style="height: 270px; overflow: auto; direction: ltr; text-align: left; padding: 10px; border-radius: 6px; width: 450px; margin-right: auto; margin-left: auto; margin-top: 10px;"> <table id = "tbl3" border="1" > {% for item in range %} <tbody id="tblbody1" style="height: 100px; overflow-y: auto; overflow-x: hidden; border-radius: 6px;"> <tr> <td><input id="name" name= "name-{{ item }}" type="text" ></td> <td><input id="family" name= "family-{{ item }}" type="text" ></td> <td><input id="age" name= "age-{{ item }}" type="text" ></td> <td> <input type="text" onclick="deleteRow(this)" value="Del"> </td> </tr> {% endfor %} </tbody> </table> </div> <div> <button class="buttons buttoning" id="btnsave" name="save" >save</button> </div> </fieldset> </div> </form> </body> </html> view.py if request.method == 'POST': for instance in range(tbl_rows_count): f1 = request.POST.get(name-' + str(instance)) f2 = request.POST.get('family-' + str(instance)) f3 = request.POST.get('age-' + str(instance)) createObj = staff.objects.create( name=f1, family=f2, age=f3, ) createObj.save() … -
Plotly Dash Integration with Django : The current path, welcome.html, didn’t match any of these While Applying Navigation on Sidebar
I have followed this Video Tutorial, and successfully applied all the step and executed. It is working fine. I am now trying to add navigation on the side bar like tables on the bottom of this sidebar navigational menu: but it is giving the following error: My master urls.py is as follows: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('home.urls')), path('django_plotly_dash/', include('django_plotly_dash.urls')), ] and my application urls.py is this: from django import urls from django.urls import path from . import views from home.dash_apps.finished_apps import simpleexample urlpatterns= [ path('', views.home, name='home'), path('tables/', views.home1, name='home1') ] While my sidebar.html is as follows: <li class="nav-item"> <a class="nav-link" href="{% url 'home1' %}"> <i class="fas fa-fw fa-table"></i> <span>Tables</span></a> </li> Moreover i am rendering this in the views.py def home1(request): def scatter(): x1 = ['PM2.5','PM10','CO2','NH3'] y1 = [30, 35, 25, 45] trace = go.Scatter( x=x1, y = y1 ) layout = dict( title='Line Chart: Air Quality Parameters', xaxis=dict(range=[min(x1), max(x1)]), yaxis = dict(range=[min(y1), max(y1)]) ) fig = go.Figure(data=[trace], layout=layout) plot_div = plot(fig, output_type='div', include_plotlyjs=False) return plot_div context ={ 'plot1': scatter() } return render(request, 'home/welcome.html', context) I am unable to understand how can I correctly locate the welcome.html so that …