Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
HOW TO DISPLAY IMAGES FROM DJANGO MODEL DATABASE IN MODAL POP UP OR LIGHTBOX
I want my lightbox or modal popup to display images from my django model, when the user upload an image to the database, the image is displayed on the webpage as modalpopup or lightbox when clicked, i achieved this by using images on my local drive. but haven't seen any solution online and on youtube for uploaded images. this only shows the first image and blank on as the next image {% extends 'base.html' %} {% load static %} {% block title %} G.F. Cakes {% endblock %} {% block content %} {% include 'nav.html' %} {% for post in post.all %} <link rel="stylesheet" href="{% static 'css/cakes.css' %}"> <div class="main"> <div class="row"> <div class="column"> <div class="content"> <img src="{{post.cake_image.url}}" style="width:100%" onclick="openModal();currentSlide(1)" class="hover-shadow cursor"> <div class="imgcaption"> <h3>{{post.cake_name}}</h3> </div> </div> </div> </div> <div id="myModal" class="modal"> <span class="close cursor" onclick="closeModal()">&times;</span> <div class="modal-content"> <div class="mySlides"> <div class="numbertext">1 / 4</div> <img src="{{post.cake_image.url}}" class="modal-img" style="width:100%"> <!-- <br /><p>{{post.cake_name}}</p> --> </div> <a class="prev" onclick="plusSlides(-1)">&#10094;</a> <a class="next" onclick="plusSlides(1)">&#10095;</a> <div class="caption-container"> <p id="caption"></p> </div> </div> </div> </div> {% endfor %} {% include 'foot.html' %} {% endblock %} my javascrpt code function openModal() { document.getElementById('myModal').style.display = "block"; } function closeModal() { document.getElementById('myModal').style.display = "none"; } var slideIndex = 1; showSlides(slideIndex); function … -
setattr() on class instance does not set value
Python 3, channels 1.x, django 1.11. The game is tron lightcycles but to turn, users must solve a math problem. multiplayer, currently 2 players max generate_first_4_problems_game func (inside channels session - see decorator @channel_session_user) is triggered at the start of a game. it sends the flux_instance to generate_first_4_problems func, which is outside the channels session (I'm not sure if this matters though). Inside generate_first_4_problems, setattr is supposed to set the values (details aren't too important, just know that the relevant (class) attributes are p1/p2-up/down/left/right (8 attributes total) and they store math problems) in the flux_instance that is being used in the channels session but that never happens. Printing getattr(flux_instance,d) (example, flux.p1up = '2 + 8') inside generate_first_4_problems exhibits expected behavior (math problem is printed), but printing inside send_answer gives a None. The focus of this question is inside send_answer, where getattr(flux_instance,d) is supposed to be some math problem, which was supposed to be defined in generate_first_4_problems (and it seems like it was, because the print statement inside of it exhibited expected behavior (a math problem for each getattr(flux_instance, d))), but it is not. Can anyone help? def is_correct_answer(problem_string, input_answer): # determines if input answer is correct for given problem string … -
Sum Foreignkey objects to loop
I'm trying create a table with 2 columns: 1) Collections and 2) Qualified Sales. Like the image above. Each book count the own qualified_sales. The Qualified sales(column in the table) must sum all qualified_sales of all books of each collection. models.py class Publishing_company(models.Model): title = models.CharField(max_length=50) class Collection(models.Model): publishing_company = models.ForeignKey(Publishing_company, on_delete=models.CASCADE) class Book(models.Model): publishing_company = models.ForeignKey(Publishing_company, on_delete=models.CASCADE) class Sale(models.Model): book = models.ForeignKey(Book, on_delete=models.CASCADE) qualified_sale = models.IntegerField(default=0) views.py def qlf_sales(request): book = Collection.objects.filter(user=request.user) qualified_sum = Sale.objects.filter(user=request.user, book__publishing_company__collection__in=book).aggregate(Sum('qualified_sale'))['qualified_sale__sum'] or 0 context = {'qualified_sum': qualified_sum} return render(request, 'template.html', context) template.html {% for collection in collections %} <tr> <td>{{collection}}</td> <td>{{qualified_sum}}%</td> </tr> {% endfor %} But this code not work. Dont appear any debug error, but only the values in the Qualified Sales' column dont appear, it was blank. If anyone can help me. Please i go a lot grateful. -
Field 'id' expected a number but got 'r' - Django form
I have a Django form that creates blog posts, however the form throws Exceptions when submitting. Strangely, however they still create these posts and I can view these on the other page. Here are my models.py, views.py, form.py code and the stack trace. Models.py from django.db import models from django.utils import timezone from django.contrib.auth import get_user_model User = get_user_model() class Author(models.Model): """ Inherits the auth user model """ user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.username class Category(models.Model): """ Generic entries so posts can be filtered """ title = models.CharField(max_length=20) def __str__(self): return self.title class News_Post(models.Model): """ Inherits Category & Author Models """ title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) date_modified = models.DateTimeField(default=timezone.now) author = models.ForeignKey(Author, on_delete=models.CASCADE) categories = models.ManyToManyField(Category) featured = models.BooleanField() post_img = models.ImageField(default='default.jpg') def __str__(self): return self.title Forms.py: from .models import News_Post from django import forms class News_Post_Form(forms.ModelForm): """ Form responsible for creating new posts. """ id = None content = forms.CharField() categories = forms.CharField() featured = forms.BooleanField() post_img = forms.ImageField() class Meta: model = News_Post fields = [ 'title', 'content', 'categories', 'featured', 'post_img', ] Views.py from django.shortcuts import render, redirect from .models import News_Post, Author from .forms import News_Post_Form from django.contrib.auth.decorators import login_required from … -
Django forms not saving
when I trying to upload a file, the line form.save(), the image is being saved in the /media folder but the webpage is showing me an error (relation "project1_document" does not exist LINE 1: INSERT INTO "project1_document" ("description", "document", ...) my model_form_upload.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form.as_p }} <button type="submit">Upload</button> </form> <p><a href="{% url 'home' %}">Return to home</a></p> </body> </html> my models.py class Document(models.Model): description = models.CharField(max_length=255, blank=True) document = models.FileField(upload_to='UserUploads/') uploaded_at = models.DateTimeField(auto_now_add=True) my forms.py from django import forms from .models import Document class DocumentForm(forms.ModelForm): class Meta: model = Document fields = ('description', 'document', ) my views.py here after saving the page is not redirecting to home insted showing me error (ProgrammingError at /model_form_upload) from django.shortcuts import render, redirect from project1.forms import DocumentForm from .models import Document from django.http import HttpResponse from django.core.files.storage import FileSystemStorage from django.views.generic.edit import FormView def model_form_upload(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): form.save(); return redirect('home') else: form = DocumentForm() return render(request, 'model_form_upload.html', { 'form': form }) -
Django annotate returning unexpected Sum value
These are my models: class Consume(models.Model): amount = models.FloatField(default=1) entry_for = models.ForeignKey( Person, on_delete=models.SET_NULL, related_name='consume_entry_for', ) class Purchase(models.Model): amount = models.DecimalField( max_digits=6, decimal_places=2, default=0.00 ) entry_for = models.ForeignKey( Person, on_delete=models.CASCADE, related_name='ledger_entry_for', ) and this is my query: person_wise_total = Person.objects.annotate( total_purchase=Coalesce(Sum('ledger_entry_for__amount'), Value(0)), total_consume=Coalesce(Sum('consume_entry_for__amount'), Value(0)) ) For example, i have an entry in Purchase amount: 2, entry_for: jhon, amount: 3, entry_for: smith amount: 5, entry_for: jhon, amount: 1, entry_for: jhon, and consume entry: amount: 1, entry_for: jhon, amount: 2, entry_for: smith, According to above data, my query Sum should return total_consume for jhon is 1, but it is returning 3 for jhon in total_consume and smith total_consume is 2, here smith result is expected but jhon result is unexpected. I guess, the problem/ wrong calculation occurring because of jhon has 3 entry in the Purchase table, so it is multpliying with total entry of person's purchase and total consume amount, i am not sure why. Can anyone please help me how can i get the correct calculated result? I want, it should return, jhon's total_purchase: 8, total_consume: 1, smith's total_purchase: 3, total_consume: 2 can anyone help me in case? -
Uploading local files remotely
Check out the image below, It is an image for a website i am working on. See the "Browse button", in the image, it is for users to upload files that are located on their pc. Imagine that i am accessing the website remotely "from another computer" and i wanna upload local files. what would be the way to upload local files where the website's source code is located while you are accessing the website remotely. Brows button is basically as that opens up a window to brows local files that are located on whatever computer you access the website from, but not from where that website is located. Thanks in advance. -
Why is my Heroku deployment not recognising my Procfile?
I'm trying to deploy my app using Heroku. I tried via CLI and also graphically in their user portal. I get this problem in the build log: Procfile declares types -> (none) It's not reading my Procfile. Here's some of the latest lines of my error logs: 2020-05-08T04:32:57.546072+00:00 app[api]: Deploy 02e1e06c by user djrgrey@gmail.com 2020-05-08T04:32:57.546072+00:00 app[api]: Release v7 created by user djrgrey@gmail.com 2020-05-08T04:33:05.475821+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=herokudanslist.herokuapp.com request_id=ff88cf27-54c2 -4611-b611-ce36c41b09f6 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T04:33:06.086210+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=herokudanslist.herokuapp.com request_id=a4 690f93-c8e3-4256-b46b-a8d1e69109c1 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T04:33:13.000000+00:00 app[api]: Build succeeded 2020-05-08T10:04:32.000000+00:00 app[api]: Build started by user djrgrey@gmail.com 2020-05-08T10:05:04.414084+00:00 app[api]: Release v8 created by user djrgrey@gmail.com 2020-05-08T10:05:04.414084+00:00 app[api]: Deploy 92e0c7b1 by user djrgrey@gmail.com 2020-05-08T10:05:37.245718+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=herokudanslist.herokuapp.com request_id=9cb80bd2-7cb6 -4e20-ad8a-e61aeeab0e02 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T10:05:39.210072+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=herokudanslist.herokuapp.com request_id=a2 9bf337-c13a-4eb7-83ef-e221bc69b6b7 fwd="118.149.66.76" dyno= connect= service= status=503 bytes= protocol=https 2020-05-08T10:05:40.000000+00:00 app[api]: Build succeeded It's not a text file. I have it in the project root directory. Just to make sure, i copied it into the root directory of that. And the … -
Django making http queries with values that is included in field (not full match)
In my Django REST-API, I can make HTTP query for example: http://example.com/api/article/?descriptions=bitcoin It returns records, where a description is exactly bitcoin. I want to make a query that finds all records where a description includes, in this case, bitcoin word. How to do it? Here is how my view class looks like: class ArticleListAPI(generics.ListCreateAPIView): queryset = Article.objects.all() serializer_class = ArticleListSerializer filter_backends = [DjangoFilterBackend] filterset_fields = ['id', 'article_name', 'descriptions'] -
Repalce the entire Django admin template
I want to replace the entire Django admin template and work with my own. I searched a lot but i found only overriding template which can't satisficate my need. how i can replace the entire admin template ? -
Waipoint.Infinite only loading next page when window is resized
I've been following the tutorial of simpleisbetterthancomplex on how to make an infinite scroll, the problem is that when I scroll to the bottom nothing happens and it will only load the next page when I'm at the bottom and the page is resized or when I open the inspector. This is the template code: {% block articles %} <section class="Posts-Section"> <div class="infinite-container"> {% if page_list %} {% for post in page_list %} {% include 'forum/post_card.html' %} {% endfor %} {% else %} <p>Não há posts</p> {% endif %} </div> {% if page_list.has_next %} <a class="infinite-more-link" href="?page={{ page_list.next_page_number }}">More</a> {% endif %} </section> {% endblock articles %} {% block js %} <script src="{% static 'forum/js/topic_details.js' %}"></script> <script> const infinite = new Waypoint.Infinite({ element: $('.infinite-container')[0] }); </script> {% endblock %} -
Django - ManyToManyField pointing to "self"
I'm trying to get a Django Model to rebuild a tree of "Founders" of a Network Marketing company, but I can't get it to work. What I'm trying to get: Every "Founder" should have a sponsor above him in the matrix (if he's the first, he doesn't!) and as many founders as he want under him (normally 3). Every founder under him should automatically get him as the sponsor. PS: I'm trying to use it with Django Admin My idea: class Founder(models.Model): name = models.CharField('Name', max_length=50) sponsor = models.ForeignKey("self", on_delete=models.PROTECT, blank=True, null=True #...) founders = models.ManyToManyField("self", #what to put here?) I tried to solve it with related names, but I can't get the ManyToManyField to point to the ForeignKey. I also tried different methods, but no one did work for me. :( Also, every time I tried to use it with Django Admin as an Inline, I got the following error: 'myapp.Founder_founders' has more than one ForeignKey to 'myapp.Founder' # I don't understand that, because Founder_founders is a Model created by Django If you could help me, I'd really appreciate it! If you need more clarification, please ask me! ;) PS: I'm pretty new here, so question might not be … -
Django -- Dynamically showing Images that are created daily
(Disclaimer -- This is my first post on stack overflow, so I'm hoping that I explain this well enough for everyone) What I want to accomplish is have an separate application generate graphs that will be placed in a directory of my Django project. Then in my template loop through and display all the graphs from that directory on the webpage. The generated graphs will be refreshed daily and will be of varying numbers depending on the day (so some days it could be 20 and/or the next it could be 50). Option 1) I don't think I want to use django manage.py collectstatic everyday. I've never gotten to the point of deploying a Django project to a server but my assumption is that I would have to collectstatic manually everyday on the server (which I could be thoroughly off on here) Option 2) I've tried creating a model Model Picture. The Char field is just my relative path to the picture. From there in my views I'm to rendering the path in the index(request) View Picture. From there in my template I'm trying to loop through the picture relative paths and show them Template Picture. When I remove photos … -
How is django rest framework utilized?
When is it required to use Django rest framework? For example if I need to use complicated Form methods, that would be complex for normal Django. -
Integrate okta with Django admin login form
I am trying to add okta OIDC integration in one of my Django sites. The site has 2 apps and these apps are using admin views only and we are not using any custom view. I want to allow users to log in from the default Django login form using Okta validation (preferably OIDC). I checked many articles and modules but I am not able to get it done because of the lack of examples available for the modules especially for beginners. Below are some modules which I tried to use but either it is a lot complicated or it needs a different login page than the Django default login page. django-oidc-provider django-admin-sso pyoidc mozila-django-oidc drf-oidc-auth Either these plugins do not support Django login form as an input form or I am not using the right plugin. Any help is appreciated. -
I always get this error:The site can't be reached
python app.py * Serving Flask app "app" (lazy loading) * Environment: production WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Debug mode: on * Restarting with stat * Debugger is active! * Debugger PIN: 312-522-468 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) This error is displayed when I deploy the server either in Django or flask. How to resolve it? -
How to allow load iframe at django page?
I have a page at django project, who contains an iframe object. But this object dont showing. what should I do to make the element work? Here is the code of page: <div class="container"> <iframe height="640" width="480" src="https://sslcharts.forexprostools.com/index.php?force_lang=7&pair_ID=962711&timescale=300&candles=50&style=line"></iframe> </div> view.py def view_rouble(request): return render(request, template_name='rouble/rouble.html') -
Django 3 invalid syntax in models.py on FileField Model
I am getting invalid syntax (, line 15) pylint(syntax-error) [15,6] which is preventing me from making migrations. Was working before I added a few fields that one was working before. It had previously worked. I added the model class choices using named groups to group the meteorites instead of inherited classes which people say causes issues from what I read. Could find anything in it that could cause it but still a possibility. I have tried deleting and reformatting it to see if the indentation was off nothing working. This usually fixes issues for me. i also tried this stackoverflow result Adding ImageField to model causes exception in django But I had pillow already installed and the unicode part did not make a difference. I also checked to see if [my parenthesis are balanced][1] which I believe they are but was a stackoverflow result. . I added the default to everything so i can makemigrations last time this worked and i made migrations and added a example. default='') it saying its this line below main_image=models.FileField(upload_to='media/', default='') blog/models.py from django.db import models from django.utils import timezone class Post(models.Model): CATEGORY_CHOICES = ( ('iron meteorites', 'iron meteorites'), ('stony meteorites', 'stony meteorites'), ('stony-iron meteorites', … -
How can I display certain fields of a django model in a template?
I would like to display certain fields for all objects of a model in a table. And I also want to render the url property of some FileFields, which are part of that model. So, I got models with obj_data = ThatObject.objects.only('field1', 'field2', 'field3') But I do not know how to access everything in the template. I could say {% for single_object in obj_data %}, but I cannot iterate over the fields of single_object. How can I do that? -
Django redirect does not change page
I am on Django 3.0.5 and in my views.py I have class SDNAList(LoginRequiredMixin, ListView): model = Protocols template_name = 'pages/protocols.html' queryset = Protocols.objects.filter(device='sDNA') login_url = '/login/' def post(self, request, *args, **kwargs): data = request.POST f = ProtocolModelForm(data) if f.is_valid(): form = f.save() # Redirect to correct page # TODO!~ print("/sdna/%i" % form.id) # return redirect("/sdna/%i" % form.id) return redirect("protocols:sdna") And in my urls.py app_name = 'protocols' urlpatterns = [ path('sdna/', views.SDNAList.as_view(), name='sdna'), In the terminal I see the GET taking place but the page does not redirect [08/May/2020 21:32:17] "POST /sdna/ HTTP/1.1" 302 0 [08/May/2020 21:32:17] "GET /sdna/ HTTP/1.1" 200 45350 -
Django allauth and Angular, how to check in Angular user is authenticated?
I'm using on the BE Django + allauth for authentication (Google) and for the front-end Angular. I have a view and a template in Django that holds the dist files from Angular. So when you get to the base URL the Angular app is bootstrapped right away. Inside Angular, I want to have a route that is accessible only for authenticated users. What would be a secure and a good way to achieve this? How can I tell in Angular that a user is authenticated or not? -
Why are my images not in one column? What am I doing wrong here?
I'm new to the front end world, and I'm wondering what I'm doing wrong here. I'm trying to get my images all in one row, but they are all over the place and my text isn't showing up correctly either. matches.html <div class="container "> <h2>It's a match!</h2> <div class = "row"> <div class="col-4"> <img src="{{ user.photo.url }}" width= "300" height= "300" object-fit = "cover" > </div> <div class="col-8"> <img src="{% static 'images/matching_cupid.png' %}" width= "300" height= "300" object-fit = "cover" > <div class="col-12"> <img src="{{ match.photo.url }}" width= "300" height= "300" object-fit = "cover" > </div> </div> <p>You and {{ match.username }} like each other!</p> <p><a href="{% url 'dating_app:messages' user.id %}">Start messaging </a></p> <br> <p><a href="{% url 'dating_app:mingle' %}">Keep mingling!</a></p> {% endblock %} -
Django display related objects inside related objects in the admin
According to my assignment admin must be able to create Polls with Questions (create, delete, update) and Choices related to this questions. All of this should be displayed and changable on the same admin page. Poll | |_question_1 | | | |_choice_1(text) | | | |_choice_2 | | | |_choice_3 | |_question_2 | | | |_choice_1 | | | |_choice_2 | | | |_choice_3 | |_question_3 | |_choice_1 | |_choice_2 | |_choice_3 Ok, it's not a problem to display one level of nesting like so on class QuestionInline(admin.StackedInline): model = Question class PollAdmin(ModelAdmin): inlines = [ QuestionInline, ] But how to do to get the required poll design structure? -
Dynamic fields in django forms
I am trying to have a custom form on django admin for my ModelB, with fields taken from other ModelA. models.py class ModelA(models.Model): source = models.CharField(max_length=80) keys = ArrayField( models.CharField(max_length=50) ) class ModelB(models.Model): characteristic_keys = JSONField() forms.py class ModelBForm(forms.ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) queryset = ModelA.objects.all() dynamic_fields = [(x.source, x.keys) for x in queryset] # New fields to be shown on admin => # Field name => "source" from modelA # Field type => multiple choice with options => "keys" from modelA for field in dynamic_fields: self.fields[field[0]] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=field[1]) def save(self, commit=True): # ...do something with extra_field here... return super().save(commit=commit) class Meta: model = Workflow fields = "__all__" admin.py class ModelBAdmin(admin.ModelAdmin): form = ModelBForm admin.site.register(ModelB, ModelBAdmin) I want a single form for ModelB on django admin, with dynamic "source" fields takes from ModelA, with multiple choice options from their corresponding "key" values in modelB. I have tried to keep information clear and understandable, please let me know if I have missed any information that might be needed to understand the problem. Any ideas to deal this problem would be a great help! -
NoReverseMatch at / Reverse for 'product' with no arguments not found
I have this error NoReverseMatch at / Reverse for 'product' with no arguments not found. 1 pattern(s) tried: ['product\\/(?P<slug>[^/]+)$'] when using Django urls patterns This is my URL patterns urlpatterns = [ path('',HomeView.as_view(),name='home'), path('checkout/',checkout,name='checkout'), path('product/<str:slug>',ItemDetailView.as_view(),name='product'), ] This is my views.py class ItemDetailView(DetailView): model = Item template_name = 'product.html' This is my models.py class Item(models.Model): title = models.CharField(max_length=100) price = models.FloatField() category = models.CharField(choices=CATEGORY_CHOICES,max_length=2) label = models.CharField(choices=LABEL_CHOICES,max_length=1) slug = models.SlugField() def __str__(self): return self.title def get_absolute_url(self): return reverse('core:product',kwargs={'slug':self.slug}) This is my base.html <li class="nav-item"> <a class="nav-link waves-effect" href="{% url 'core:checkout' %}" target="_blank">Checkout</a> </li> <li class="nav-item"> <a class="nav-link waves-effect" href="{% url 'core:product' %}" target="_blank">Product</a> </li>