Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Visual tree representation After filtering
I'm working on a Django app, I want to make some kind of tree of nodes and leafs like this example. How I can implement that using html-css-javascript ? Is there any library or framework that helps ? -
Calling a DRF API via javascript: properties may not be accessed on strict mode functions
I have a very simple model which I call via javascript unsuccessfully: model: class Product(models.Model): name = models.CharField("name", max_length = 32, unique = True) file = models.ImageField(upload_to = "images") view: class ProductDataViewSet(viewsets.ViewSet): def list(self, request): query = Product.objects.all() results = PSerializer(data = query, many = True) results.is_valid() return Response(data = results.data) Serializer: class PSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ["pk", "name", "file"] api call: var testing = async function() { const data2 = await $.ajax({url: "api/pds/"}); console.log(data2) } This returns me: django restframework "'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them but ONLY when I call it via await. If I just go to 127.0.0.1:8000/api/pds i get a correct output: HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "pk": 2, "name": "cafe pic", "file": "/media/images/cafe_2020.bmp" }, { "pk": 3, "name": "test pic", "file": "/media/images/test.bmp" } ] I have no idea what goes wrong why. I have a multiple similar API endpoints within the same app that work just fine, as long as I do not choose this model. The only difference is the models.ImageField(upload_to = "images") - I know when … -
ckeditor mardown bar showing in admin page but not in htm template
im trying to include ckeditor ,which work in the admin page perfectly but not showing the mardown bar at all in a regular template with a form <form method="post"> {{ form.as_p|safe}} {{ form.media }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> the markdown from my admin page on the same form is workin as expexted. seems like this line {{ form.media }} isn't working , any idea why ?? -
Unable to display image in django when the url is correct
I'm new to Django. In my app, I'm working on an image uploading and displaying function. I have tried setting up the MEDIA_URL and Media_ROOT. I also add the static path to the urls.py file and make sure that in HTML template object.image.url is used. However, the image is not displayed. Any help is greatly appreciated! My code is as followed: urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path("admin/", admin.site.urls), path("", include("auctions.urls")) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py class ListingForm(ModelForm): def __init__(self, *args, **kwargs): super(ListingForm, self).__init__(*args, **kwargs) for field in iter(self.fields): self.fields[field].widget.attrs.update({ 'class': 'form-control' }) class Meta: model = Listing fields = ['title', 'description', 'current_price', 'image', 'category'] def index(request): return render(request, "auctions/index.html", { "active_listings" : Listing.objects.all() }) def createListing(request): if request.method == "POST": listing_data = ListingForm(request.POST, request.FILES) if listing_data.is_valid(): title = listing_data['title'] description = listing_data.cleaned_data['description'] current_price = listing_data.cleaned_data['current_price'] if listing_data.cleaned_data['image']: image = listing_data.cleaned_data['image'] else: image = None category = listing_data.cleaned_data['category'] listing = Listing(title=title, description=description, current_price=current_price, image=image, category=category) listing.save() return HttpResponseRedirect(reverse("index")) return render(request, "auctions/createListing.html", { "listingForm" : ListingForm() }) models.py class Listing(models.Model): class Category(models.TextChoices): FASHION = 'FA', _('Fashion') TOYS = 'TO', _('Toys') ELECTRONICS = 'EL', _('Electronics') HOME = … -
assign task no to the current user in viewflow
I have been using viewflow for a while, and I managed to create my process without any problem. But now I need someone to review the work from someone else. I don't want to create roles for that simple task, because I want everybody to be able to review somebody's work at any time. In other words, there is one task (task1) that can be executed for everybody, but it cannot be executed for the same person that finished the previous task. task1 = ( flow.View( UpdateProcessView, fields=["quality_check", "quality_check_comments"], task_description="writte comments" ).Permission( auto_create=True ).Next(this.task2) ) task2 = ( flow.View( UpdateProcessView, fields=["quality_check_completed"], task_description="Perform a quality control on the work instructions" ).Permission( auto_create=True ).Next(this.check_qa_manual) ) From Django-viewflow how to get the current user? I understand that I can assign the task to the user that created the task or the owner of a previous task, but I want the contrary. Is there a way to say .Assign(this.start.(not)owner) or .Assign(this.start.(not)created_by) ? -
django: user activation during email confirmation
Unfortunately. user is not going to be activate views.py: code = random.randint(1000, 9999) def register_view(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] password1 = request.POST['password1'] email = request.POST['email'] global user user = User(email=email, username=username) user.set_password(password) else: ... again views.py another def def email_activation(request): if request.method == "POST": global code email_activation = request.POST['email_activation'] if str(email_activation) == str(code): user.is_active = True return redirect('account') else: ... please help me -
"Django" Add friend request error (No User matches the given query)
I am trying to add a button to send a friend request to another user, but I keep getting the error (No User matches the given query). I have a 'Add Friend' button on the profile.html page of the user which works fine, I can't figure out what is going wrong, but on the users_list.html, the button comes back with this error. I'm still new to Django and learning, so would appreciate any help. error : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/users/friend-request/send/2/ Raised by: users.views.send_friend_request No User matches the given query views.py from django.shortcuts import render, redirect, get_object_or_404 from .models import Profile from feed.models import Post from django.contrib import messages from django.contrib.auth.decorators import login_required from django.contrib.auth import get_user_model from django.conf import settings from django.http import HttpResponseRedirect from .models import Profile, FriendRequest from .forms import UserRegisterForm, UserUpdateForm, ProfileUpdateForm import random from django.core.mail import send_mail @login_required def users_list(request): users = Profile.objects.exclude(user=request.user) sent_friend_requests = FriendRequest.objects.filter(from_user=request.user) sent_to = [] friends = [] for user in users: friend = user.friends.all() for f in friend: if f in friends: friend = friend.exclude(user=f.user) friends+=friend my_friends = request.user.profile.friends.all() for i in my_friends: if i in friends: friends.remove(i) if request.user.profile in friends: friends.remove(request.user.profile) random_list = … -
Django is appending unwanted characters to Imagefield name attribute
I am writing a test for my Imagefield model that checks its relative path name, but it is not passing because the __str__ method returns the file path + some unwanted characters. For example, a file created as test_image.png is returned as test_image_ak0LKei.png, despite the fact that I am explicitly defining the file name. Every time a new file is created the appended part changes, it can return test_image_HqOXJc4.png, for example. This only happens when I am creating a dummy image file for the tests. When I upload a real image in Django's admin, it just returns the file path without any modifications. I am using Sqlite for tests and Postgres for the development, as the development database is in Heroku and it does not allow table creation I tried to change how I create the dummy file, like using a bytes object, using b64decode() with SimpleUploadedFile() from django, but the results are the same. My models: class Image(models.Model): image = models.ImageField(upload_to='post_images/') alt_tag = models.CharField(max_length=125, blank=True) def __str__(self): return self.image.name My test. The last thing I tried is using the static method below: class ImageTestCase(TestCase): @staticmethod def get_image_file(name='test_image.png', ext='png', size=(50, 50), color=(256, 0, 0)): file_obj = BytesIO() image = PIL_IMAGE.new("RGBA", … -
Django: Add subquery to a nested model
I have the following models in my project. An SRV contains many projects, and each project contains several tasks. I am detailing each SRV in a template and showing a list of all associated projects. class Srv(models.Model): srv_year = models.CharField(max_length=4) class Project(models.Model): srv = models.ForeignKey(Srv, on_delete=models.CASCADE, null=True, blank=True) class Todo(models.Model): project = models.ForeignKey(Project, on_delete=models.CASCADE, null=True, blank=True) state = models.BooleanField(blank=True, null=True, default=False) in views.py I want to get the completed tasks associated with each project, but I always get all the tasks associated with all projects from the SRV (main model) queryset = Srv.objects.annotate( todo_done=Round(Count('project__todo', filter=Q(project__todo__state=True)) * 100.0 / Count('project__todo')), ) How can I send a new data to the project list contained in an SRV? -
Invalid block tag on line 10: 'static'/css/all.css''. Did you forget to register or load this tag?
am getting Invalid block tag on line 10: 'static'/css/all.css''. Did you forget to register or load this tag? when i run my django app. here is my code: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <!-- Font Awesome --> <link rel="stylesheet" href="{% static'/css/all.css'%}"> <!-- Bootstrap --> <link rel="stylesheet" href="{% static'/css/bootstrap.css'%}"> <!-- Custom --> <link rel="stylesheet" href="{% static'/css/style.css'%}"> <title>BT Real Estate</title> </head> here is my static settings STATIC_ROOT= os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [`enter code here` os.path.join(BASE_DIR, 'btre/static') ] -
how to pass django view data in js to get product id accordingly
the problems is i have passing data from view to product template , when i click add to cart i have to get product id accordingly using js how can i do this inside templates it work but when i apply inside script it doesn't work is there any method to access / get data my views.py def product(request): productbyid = None categories = ProductCategory.get_all_categories() products = TopList.get_all_products() categoryID = request.GET.get('category') if categoryID: productbyid =TopList.objects.filter(category=categoryID) else: productbyid = TopList.get_all_products() data = {} data['categories']:categories data['productbyid'] =productbyid data['products'] = products data['categories'] =categories return render(request,'product.html',data) my product.html % for pbyid in productbyid %} <div class="card card_body m-2 p-0 container" id='{{pbyid.id}}'> <div> <div> <a href="/viewpage/{{pbyid.id}}"><div class='imagestyle' ><img class="card-img-top " src="{{pbyid.image}}"width="500" height="200" alt="Card image cap "></div></a> <span class="top-left">{{pbyid.discountpercentage}}% off</span> </div> <div class="card-body"> <h5 class="card-title cardtitle">{{pbyid.title}}</h5> <div><p class="carddesccrip">{{pbyid.desc}} </p></div> <div class='pricce_card'> <span class='price'> <b>M.R.P</b> <strike class='carddesc'>RS {{pbyid.discountPrice}}</strike></span> <span class='final_price'><b>RS. {{pbyid.finalprice}}</b></span> </div> </div> <div class="card-body"> {% comment %} /viewpage/{{pbyid.id}} {% endcomment %} <button href="" class="btn btn-lg btn-block addbtn caddtocart" onclick="myFunction()" > Add to cart {{pbyid.id}} <i class="fa fa-plus float-right align-center p-2 plusbtn" aria-hidden="true"></i></button> </div> </div> </div> {% endfor %} js , my try here i when i click caddtocart btn i have to get product id accordingly … -
Django: Access custom login page along with AD authentication
I am writing a Django application for a company and they have requested me to integrate AD authentication as they already have groups in their Active Directory for all their tasks. I have found a potential solution here: Automatic Login in a Django Application Using External Authentication (It is not yet tested for production) Now, the problem that I am facing is that I can't access the custom/Django's default login system. I need the custom page in case someone outside the AD group wants to access the application (approved by the company). How can I access the login page, in case there is no AD group member logged in? -
django cache_page how to set version
I can set version by cache.set: cache.set(key, value, timeout=60, version=1) but how to set by cache_page decorator? like: @cache_page(60, version=1) def view(request): -
Update model that is connected via ForeignKey
Hi I have models that are contectet via foregin key. I can have multiple orders so let's say that i have 3 orders. 2xTshirt 1xPants and 4xHats. How can I acces each product and change the stock of them based on quantity of an order. views order = Order.objects.get_or_create(customer=customer, complete=False) order_items = OrderItem.objects.filter(order=order) for item in order_items: item.product.stock = int(item.product.stock) - int(item.quantity) item.transaction_id = transaction_id item.save() models class Product(models.Model): title = models.CharField(max_length=70, null=True, blank=True) producent = models.CharField(max_length=40, null=True, blank=True) stock = models.PositiveIntegerField(null=True, blank=True) class OrderItem(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, blank=True, null=True) quantity = models.IntegerField(default=0, null=True, blank=True) -
How can i display a custom method to a model in a template using views(generic)?
#Hello people. I have ran into a problem and am kindly asking you to help me. So i have added a custom method to my fee profile model, and i wanted it to calculate for me the fee balance when a fee instance is created. First, before adding the custom method, everything was working out well. I could add a fee profile instance in the django admin without getting errors. Also, i have included a dictionary that stores the fee payment history and am unable to figure out a way to display the fee payment history on a template.I am running django 3.1.4, and using python 3.8.5. Here is my code: #This is the error i got."str returned non-string (type Child)". Remember all was working well till i introduced the fee_status() custom method. '''# Fee model #the admin.py code @admin.register(FeeProfile) class FeeProfile(admin.ModelAdmin): list_display = ( 'child', 'amount_paid', 'date', 'fee_status' ) list_filter = ['date'] search_fields = ['child'] class FeeProfile(models.Model): child = models.ForeignKey('bjs_main.Child', on_delete=models.CASCADE) parent = models.ForeignKey('bjs_main.Parent', on_delete=models.CASCADE) mpesa_code = models.CharField(max_length=10, primary_key=True) amount_paid = models.IntegerField(default=0) date = models.DateTimeField(auto_now_add=True) def __str__(self): return self.child def fee_status(self): global total_amount_paid total_amount_paid += self.amount_paid fee_balance = term_fee - total_amount_paid payment_history = { 'amount_paid': self.amount_paid, 'date_paid': self.date … -
Mock a formset save_formset method django forms?
I am new to writing tests and wanted to know the right approach on how I can mock a ModelAdmin save_formset functionality. Basically, I don't want to create a formset and want to mock the value of the formset.forms and pass it to the function so that it just tests the important part of the save_formset function. However, at the end of the function it still tries to call the ModelAdmin formset.save() method and that's where I get a NoneType attribute because in reality I am not passing an actual formset to the function. This is what I tried so far admin.py def save_formset(self, request, form, formset, change): forms = self.get_formset_forms(formset) for f in forms: obj = f.instance if not hasattr(obj, "creator"): obj.creator = request.user formset.save() def get_formset_forms(self,formset): return formset.forms tests.py @patch("core.apps.survey.admin.SurveyAdmin.get_formset_forms") def test_save_formset(self,mock_get_formset_forms,mock_formset_save): user = mixer.blend(User) mock_get_formset_forms.return_value = [{'instance':{'iss':user}}] mock_formset_save.return_value=1 site = AdminSite() survey_admin = admin.SurveyResponseAdmin(Survey, site) survey_admin.save_formset(request=None, form=None, formset=None, change=None) error log survey_admin.save_formset(request=None, form=None, formset=None, change=None) core/apps/survey/tests/test_admin.py:56: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ … -
Django: Get objects of first model by comparing attribute of second OneToOne related model
I have two models, User and Card. One user has one card. I need to get objects of User if the 'card_written' of Card model is False in a view. class User(model.Model): phone = PhoneNumberField(null=False, blank=False, unique=True) email = models.EmailField(verbose_name="email", max_length=60, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) class Card(models.Model): user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) card_number = models.CharField(max_length=200) card_written = models.BooleanField(default=False, null=False) card_write_date = models.DateTimeField(null=True, blank=True) card_delivered = models.BooleanField(default=False, null=False) -
Django superuser/admin doesn't login on deployed web app (Digital ocean)
I have developed and deployed a Django web-app on digitalocean following this article from digital ocean but i have an issue logging in after successfully adding a superuser. Locally (on the server i.e http://server_domain_or_IP:8000) i can log in and add data BUT when i add NGINX, i can not login. The rest of the web-app works fine i.e the staticfiles are fine. Here is my GUNICORN FILE [Unit] Description=gunicorn daemon After=network.target [Service] User=ronald Group=www-data WorkingDirectory=/home/user/projectfolder ExecStart=/home/user/projectfolder/virtualenv/bin/gunicorn --access-logfile - --workers 3 --bind 0.0.0.0:8000 projectname.wsgi [Install] WantedBy=multi-user.target And here is the NGINX FILE server { listen 80; server_name server_domain_or_IP; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/user/projectfolder; } location /media/ { root /home/user/projectfolder; } location / { include proxy_params; proxy_pass http://0.0.0.0:8000; } } I have tried using the projectname.sock file as described in the article above but it's still the same error. -
Field 'id' expected a number but got <built-in function id> error
I want to add a favorites button in my template but seem to run into this error. Views.py class PropertyDetailSlugView(DetailView): queryset = Property.objects.all() template_name = "property/property_details.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) slug = self.kwargs.get('slug') obj = self.get_object() tags = obj.tag_set.all() if self.request.user.is_authenticated: for tag in tags: new_view = TagView.objects.add_count(self.request.user, tag) featured = list(Property.objects.filter(featured=True)) property_type = Category.objects.all() property_list = list(Property.objects.all()) city = City.objects.all().annotate( num_property=Count("property")).order_by("-num_property") favorite_property = get_object_or_404(Property, id=id) is_favorite = False if favorite_property.favorite.filter(id=self.request.user.id).exists(): is_favorite = True context['featured'] = featured context['is_favorite'] = is_favorite context['property_type'] = property_type context['property_list'] = property_list context['city'] = city return context Urls.py from django.contrib.auth.decorators import login_required from django.conf.urls import url from django.urls import path, re_path from .import views from .views import ( PropertyDetailSlugView, ) app_name = 'property' urlpatterns = [ path('<slug:slug>/', login_required(PropertyDetailSlugView.as_view()), name='details'), path('<int:id>/favorite_property/', views.favoriteProperty, name='favorite_property'), ] The error seems to occur while using the Id in Class Based Views is there a different way of using the Id's while using CBV. Any insight would be greatly appreciated. Thanks. -
How can you delete data after each output in django?
I'm building a scrapper that prints out the results on the same page, but whenever I try to search for new results, the old ones still appear. Meaning that the HTML doesn't get deleted at all after each search. I want that the data of the previous emails searched gets deleted for new ones. How can you do that? The code for printing emails: {% for email in email_list %} <p id="results"> {{ email }} </p> {% endfor %} Email list: def scrap(request): url = request.GET.get('Email') crawl = EmailCrawler(url) target = crawl.crawl() email_list = crawl.emails # or whatever class-level variable you use return render(request, 'leadfinderapp/emailsearcher.html', {"email_list": email_list}) For you to understand it better I will put two images: As you can see by the images, the first domains results appear correctly (which would be 3 emails) and the second domains results also appear, but it appears with the results of the first search. I want it to reset the results of the first instead and search for the new ones. -
Reload Bootstrap Toast without reload the page (with django)
I have a bootstrap toast (v 4.5.3) <div class="toast d-flex toast-success" role="alert" aria-live="assertive" aria-atomic="true" data-delay="3000"> <div class="toast-header toast-success"> <i class="fas fa-check"></i> </div> <div class="toast-body"> {{message}} </div> </div> After submiting a form with Ajax POST I want to reload the Toast to show the new message generated in my django view. Can I do that without reloading the entire page ? -
Django Forms - how to add the + sign for a Many2Many field
enter image description hereRelated to Django Forms and Many2Many I have tried to look for ways to add the + to my django form when I want to add a new post to my webpage. What I'm looking for is a similar function as the one in admin module. See picture. I have tried to read though the docs but not sure what to look for. Have anybody build something similar? br Lars -
use a django view in python script
In my django project, I have a url which on GET request, loads a template that gets converted to pdf using pdfkit. I need to use this url in my script so that I'm able to load the template and create the pdf using the script. In urls.py: re_path(r'^/send-invitation/(?P<policy_id>\d+)/$', views.send_invitation), In my views.py def send_invitation(request): //logic to call required details //load the template and create pdf // this part works fine return render(request, 'send_invitation.html',{ 'some_objects':some_objects, }) In my python script, I have: import os, sys import requests proj_path = sys.argv[1] + "myproject/" database = sys.argv[3] os.environ["DJANGO_SETTINGS_MODULE"] = "myproject." + sys.argv[2] sys.path.append(proj_path) # This is so my local_settings.py gets loaded. os.chdir(proj_path) # This is so models get loaded. from django.core.wsgi import get_wsgi_application application = get_wsgi_application() from account_engine.models import * from django.conf import settings import datetime import string url = settings.WEB_ROOT + '/send-invitation/%s' % (policy.id) print('url being used %s' % url) from urllib.request import urlopen response = urlopen(url) simply loading the url in the browser results in template getting loaded and pdf getting created as required. However, same does not work in the script. My understanding is that since I'm doing urlopen, I'm sending a GET request to the url which ideally … -
How to add data to html table and get those data by clicking on corresponding rows
I'm adding table data using Java script. I need code for click event that picks all data from clicked row .I have a table in my code and all the data are added using java script. Now i need to get those added data by clicking corresponding rows. It can be achieved easily by using html elements but for some reasons i cant use the that method. I must use java script to add the data. I am using Django My code looks something like {% extends 'dashboard.html' %} {% block maincontent %} <form method="POST" action="showtrip" id="tripfrm"> {% csrf_token %} <label for="vn">Vehicle No</label> <input type="input" id="vn" name="vn" value="" > <label for="datefrom">Starring Date</label><input type="date" id="datefrom" name="datefrom"> <label for="starttime">Starring Time</label><input type="time" name="starttime"> <label for="dateto">Ending Date</label><input type="date" id="dateto" name="dateto"> <label for="endtime">Ending Date</label><input type="time" id="endtime" name="endtime"> <input type="submit" class="button1" id="sub" value="Check"> </form> <table class="listtbl" id ="listtbl" name= "listtbl" style="cursor: pointer;"> <tr> <th><label>Starting time</label></th> <th><label>Starting point</label></th> <th><label>reached time</label></th> <th><label>Destination Point<label></th> <th><label>AVG. speed<label></th> <th><label>Max Speed<label></th> <th><label>Engine ONTime<label></th> <th><label>Distance<label></th> <th><label>View Rout</label></th> </tr> </table> <script> $( "#vn" ).focus(function() { if(this.value=="select vehclle no"){ this.value="" } }); $( "#vn" ).focusout(function() { if(this.value==""){ this.value="select vehclle no" } }); </script> <script> $(function () { $("#vn").autocomplete({ source: '{% url 'vhnoload' %}' }); }); … -
How can we notify the admin about newly added project by user, by defualt project is_active=False
How the admin will be notified on the dashboard (not by mail), and verify all the projects or can decline the projects. class Compaigns(models.Model): nameOfDeceased = models.CharField(max_length=100, null=False, blank=False) nameOfDeceasedEn = models.CharField(max_length=100, null=False, blank=False) projectName = models.CharField(max_length=255, null=False, blank=False) projectNameEn = models.CharField(max_length=255, null=False, blank=False) phone = models.CharField(max_length=255, null=False, blank=False) image = models.ImageField(upload_to='projects/compaigns/%Y/%m/%d', blank=True, null=True) is_compaign = models.BooleanField(default=True) **is_active = models.BooleanField(default=False)** detail = models.TextField(blank=True, null=True) detailEn = models.TextField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) suggestedDonation = models.DecimalField( max_digits=10, decimal_places=3, default=0.000) compaignCategory = models.ManyToManyField(CompaignCategory) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.nameOfDeceased class Meta: verbose_name_plural = "Compaigns"