Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django-filter with checkboxes instead of option list
I have a model containing three fields: title= models.CharField(max_length=250) cat1 = models.CharField(max_length=250, choices=(('g1',"Game1"), ("g2", "Game2"), ("g3", "Game3"), ("g4", "Game4"))) cat2 = models.CharField(max_length=250, choices=(('type1',"Drawn"), ("type2", "Computer graphic"), ("type3", "Pixelart"))) And in filters.py I have: import django_filters from .models import MyModel from django import forms class ArtFilter(django_filters.FilterSet): class Meta: model = MyModel fields = ['cat1', 'cat2', ] Don't know if views.py does matter in this case, but here it is: def search(request): art_list = MyModels.objects.all() art_filter = ArtFilter(request.GET, queryset=art_list) return render(request, 'search/art_search.html', {'filter': art_filter}) Everything's fine except that I need to let people choose more than one game or art type, so they could click on Game1, Game2 and Drawn to see all drawn images from both games. How can I achieve this? -
How to loop through model and display it on the modeladmin in django?
i'm new to python and django and stackoverflow too. Id like to know if there is a way to display on my admin section the number of party that an author have in the Author admin section call num_party ? To me i have to loop through the model and count how many party an author has, it's seems easy to say but not easy to do, so someone could help me ? Here my Party Model class Party(models.Model): title = models.CharField(max_length=200) place = models.ForeignKey('Place', on_delete=models.CASCADE, null=True) author = models.ForeignKey('Author', on_delete=models.SET_NULL, null=True) date = models.DateField(null=True, blank=True) genre = models.ManyToManyField(Genre, help_text='Select a genre for this partty') ticket_available = models.IntegerField() ticket_price = models.PositiveIntegerField(default=5) language = models.ManyToManyField('Language') insider_secret = models.ManyToManyField('InsiderSecret') #benef = models.IntegerField(default=5) def get_benef(self): return self.ticket_available * self.ticket_price benef = property(get_benef) def __str__(self): return self.title def get_absolute_url(self): return reverse('book-detail', args=[str(self.id)]) def display_genre(self): return ', '.join(genre.name for genre in self.genre.all()[:3]) display_genre.short_description = 'Genre' def display_secret(self): return ', '.join(insider_secret.secret for insider_secret in self.insider_secret.all()[:3]) display_secret.short_description = 'Insider Secret' class Author(models.Model): """Model representing an author.""" username = models.CharField(max_length=100, help_text="How do you want to be call by people as organisor ? ", default="Bestpartyorganisorintown") first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) date_of_birth = models.DateField(null=True, blank=True) class Meta: ordering = … -
django search only some words in a precise order
Hi I'm using django in Mayna EDMS index function to search only some words in a precise order within a text. For example I need to search: "Date: * ** * 2020 alle ore" where "*" character could be any character. How can I manage this search ? -
Run a bash script from another user with Django
this is my first Django project, I apologies if I say some nonsense To start a game server, I have to login with ssh as the user running the server, then type./server start to start it. I want to be able to run this command from a webapp. As of now, I've managed to do this on Django. What I want to do is that when I press the "Start" button, this commands run on the server side: su - gameuser -c '/home/gameuser/server start' > /dev/null 2>&1 The problem I'm facing is that I don't know how to login as the gameuser since I'm not a running the webapp as a sudo user. How can I approach this problem? Thanks in advance :D -
Override Django's AuthenticationForm's fields
I am using Django's autentication backend and it works fine, but I want to give the username and password fields a custom css class. I have been trying to look for a solution but I cannot find anything here or anywhere else. This is what I have done so far: project/forms.py: from django import forms from django.contrib.auth.forms import AuthenticationForm class LoginForm(AuthenticationForm): username = forms.CharField(widget=forms.TextInput(attrs={'class': 'form-control form-control-lg'})) password = forms.CharField(widget=forms.PasswordInput(attrs={'class': 'form-control form-control-lg'})) project/urls.py: from django.contrib import admin from django.urls import path, include from .forms import LoginForm urlpatterns = [ path('accounts/', include('django.contrib.auth.urls'), {'authentication_form': LoginForm}), ] accounts/login.html: <form method="POST"> {% csrf_token %} <div class="form-group"> {{ form.username }} {{ form.password }} <button type="submit" class="btn btn-primary btn-lg btn-block">Sign in</button> </form> The login system works but I cannot get the css changes to show up. I inspected the username and password fields but they are not showing up in the browser at all. I am guessing I am missing something somewhere? Any help would be really appreciated! -
Sort Blog Post comments by date DJANGO
Hi i have a problem with comments on my Blog app in Django. Everything is working fine except that i want to display comment sorted by date (newest on top) o and it'll be great i'll be able to put in to the author field user that is actually loged in.. TY views.py @login_required def add_comment_to_post(request, pk): post = get_object_or_404(Post, pk=pk) if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.save() return redirect('post-detail', pk=post.pk) else: form = CommentForm() return render(request, 'blog/add_comment_to_post.html', {'form': form}) models.py class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE,related_name='comments') author = models.CharField(max_length=100) text = models.TextField() created_on = models.DateTimeField(default=timezone.now) active = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('author', 'text', 'created_on') -
How to get data from nested HTML using BeautifulSoup in Django
I am trying to learn web scraping and I'm stuck at a point where the data I want is wrapped by a div tag as so: <div class="maincounter-number"> <span style="color:#aaa">803 </span> </div> There are several data like that and I need all (eg. 803). So i guess I need to do soup.find_all(...) but I don't know what to put inside. Anyone help? I am working in python (Django.) -
I Cant View my posts for this Blog in the Index.html page
Hey guys i am to view my blog post, but i cannot seem to view any of the blog post on the loaded html page, what could be the problem i have tried to troubleshoot to see the problem but i cant come with any solution, please i would need some feedback on what i am doing wrong my index {% extends "base.html" %} {% block content %} <style> body { font-family: "Roboto", sans-serif; font-size: 18px; background-color: #fdfdfd; } .head_text { color: white; } .card { box-shadow: 0 16px 48px #E3E7EB; } </style> <header class="masthead"> <div class="overlay"></div> <div class="container"> <div class="row"> <div class=" col-md-8 col-md-10 mx-auto"> <div class="site-heading"> <h3 class=" site-heading my-4 mt-3 text-white"> Welcome to my awesome Blog </h3> <p class="text-light">Great Post to help you with your day! &nbsp </p> </div> </div> </div> </div> </header> <div class="container"> <div class="row"> <!-- Blog Entries Column --> <div class="col-md-8 mt-3 left"> {% for post in post_list %} <div class="card mb-4"> <div class="card-body"> <h2 class="card-title">{{ post.title }}</h2> <p class="card-text text-muted h6"> {{ post.created}} </p> <p class="card-text">{{post.content|slice:":200" }}</p> <a href="{% url 'post_detail' post.slug %}" class="btn btn-primary">Read More &rarr;</a> </div> </div> {% endfor %} </div> {% block sidebar %} {% include 'sidebar.html' %} {% endblock … -
Reduce number of database queries, initiated from django "for loops" in templates - Django website extremely Slow
I'm facing difficulties optimizing the load time of my website. I installed Django Debug Toolbar to see from where my 3 to 4 seconds request delays come from. The fact is that it comes from many duplicated SQL Queries. Recently, I optimized my view code so there is no query duplication, but the essential part of these comes from my template rendering, especially from my for loops (which are everywhere, sadly). Here is an example : - This page shows Transactions, divided in several sections. It is paginated by 48. Because of the organization of my template, I'm forced to "for loop" every transaction linked to the user in each category and do some if/elif/else treatments. -> From what I saw by removing 5 of the 6 for loops, it reaches my RDS database EVERYTIME a for loop is started, which does not sound efficient, and takes forever to load. I hope someone can help me. I've seen some caching methods out there but I don't know if my case applies for such thing. -
How to get the information from information_schema on Django
I have viewset with cache. in views.py def maybe_decorate(decorator): #check the last update here #SELECT UPDATE_TIME FROM information_schema.tables WHERE table_schema = DATABASE() and TABLE_NAME = 'tweet' return decorator if no_update else lambda x: x class TweetViewSet(viewsets.ModelViewSet): queryset = Tweet.objects.all().order_by('id') @maybe_decorate(method_decorator(cache_page(60*60*2))) @maybe_decorate(method_decorator(vary_on_cookie)) Now,I want to check if the table is updated or not from information_schema. (If there is any alternative way to know the table is updated or not, please let me know the idea) Normally I access the table data with model but in this case, how can I get the information_schema.tables from django?? -
Django Channels: Unable to execute synchronous code in asynchronous function
I think possibly I am being quite daft, however... I have just started learning Django Channels (many thanks Andrew Godwin!) and have dabbling about with around with the tutorial code. I cannot figure out how to execute synchronous code (calling a synchronous function or whatever) from within in an asynchronous (AsyncWebsocketConsumer) function/class. There are two methods (sync_to_async & async_to_sync) which I was thought were meant to allow this kind of thing (https://www.youtube.com/watch?v=cNbcHvRvJsg) but I can't get it to work. At the moment they both print all the messages queued while the server is running when the server restarts. This is my first foray into async Django... surely it must be possible to, for instance, print to the console from inside an async function?? Thanks in advance. Channels consumer (as per tutorials, with added print statements): import json from asgiref.sync import sync_to_async, async_to_sync from channels.generic.websocket import AsyncWebsocketConsumer class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_name = self.scope['url_route']['kwargs']['room_name'] self.room_group_name = 'chat_%s' % self.room_name sync_to_async(print('connected - sync_to_async')) async_to_sync(print('connected - async_to_sync')) # Join room group await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def disconnect(self, close_code): # Leave room group await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) # Receive message from WebSocket async def receive(self, text_data): text_data_json = … -
Uploading an imaging using Django Admin, image is located successfully but getting this error The 'image' attribute has no file associated with it
Error Appearing when trying to show the image in the front end -
Get the display name dynamically inside Django view?
I have a model called person like this class person(models.Model): choice1 = ("a","DisplayNameA", "b", "DisplayNameB") choice1_field = models.CharField(max_length=1, choices=choice1) choice2 = ("c","DisplayNameC", "d", "DisplayNameD") choice2_field = models.CharField(max_length=1, choices=choice2) # and so on, there are many fields like these After this, I am trying to generate a CSV file in my views I can loop through all the fields I need and then access the values dynamically like this getattr(person_object, field_name) However this returns "a", "b" and so on. I know I can access the display name using get_FOO_display(), where foo is the field's name. However, as the retrieval of the field is happening dynamically, is there a way to access the display name of a field dynamically? Without having to bind functions? -
Django modify field name in Q object
I have a function that returns a Django Q object that's used for filtering. I don't have the ability to edit this function. Is there an easy way to rename a field/attribute name? Ideally I'd like to do this without creating my own function. For example, how could you change date__range to paid_at__range? <Q: (AND: ('date__range', [datetime.date(2020, 4, 8), datetime.date(2020, 4, 12)]), ('status__in', ['2', '3']))> I started doing something like this but in my opinion it becomes hard to follow and would probably be more readable if I just created another function to get the filters. filters = self.get_filters() for f in filters: if isinstance(f, Q): for child in f.children: print(child) -
Tuple Error When Using Queryset to Match a user with a specific foreign key to key
I'm trying to create an api that returns Orders that satisfy these requirements: Status = ready, no other driver has picked it up, and the driver is assigned to that venue. The driver should only be able to view orders from their assigned location. Everytime I call api, I get the error saying: 'tuple' object is not callable. How do I format and return all the items in the query, properly in a JsonResponse? I do not understand the error. Here is the result of the query TypeError at /api/driver/orders/ready/ 'tuple' object is not callable /apis.py in driver_get_ready_orders @csrf_exempt def driver_get_ready_orders(request): driver = CustomJWTAuthenticator().authenticate(request)[0].driver queryset = Order.objects.filter( status=Order.READY, driver=None).order_by("-id"), if driver.dispensary: queryset = queryset(dispensary=driver.dispensary ... ) orders = Order.objects.filter( queryset, many=True, context={"request": request} ▶ Local vars Variable Value driver <Driver: Malcom Brooks> queryset (<QuerySet [<Order: 10>, <Order: 8>]>,) request <WSGIRequest: GET '/api/driver/orders/ready/? Here is my Api: def driver_get_ready_orders(request): driver = CustomJWTAuthenticator().authenticate(request)[0].driver queryset = Order.objects.filter( status=Order.READY, driver=None).order_by("-id"), if driver.dispensary: queryset = queryset(dispensary=driver.dispensary ).all() orders = Order.objects.filter( queryset, many=True ) return JsonResponse({"orders": orders.data}) Order and Driver model: class Order(models.Model): PICKING = 1 READY = 2 ONTHEWAY = 3 DELIVERED = 4 CANCELED = 5 STATUS_CHOICES = ( (PICKING, "Your Order Is Being … -
How download Django website on host(server) with CPanel
Hi i need very detail instruction how download Django website on host. I use FileZilla. In mysite i have main folder mysite wich have wsgi.py. Write which screenshot you need i wiil add My Django web site on host inside mysite My Python app in CPanle Second screen my Python app in CPanel -
Django filtering by two categories logic
def post_list(request): school_slug = request.GET.get('school', None) category_slug = request.GET.get('category', None) if VideoPost.objects.filter(approve = 1).exists(): posts = VideoPost.objects.all().filter(approve = 1) if school_slug: posts = posts.filter(school=school_slug) if category_slug: posts = posts.filter(category=category_slug) posts = posts.order_by('-date_posted') return render(request, 'stories/post_list.html', {'posts': posts}) return render(request, 'stories/no_post.html') I'm filtering the posts by getting URL parameter which would be 1) example.com/post/ to display all posts 2) example.com/post/?category=something to display all posts with something category 3) example.com/post/?category=something&school=someschool to display with two filters 4) No post.html page when no post under the category. The first three filtering works fine, but how should I filter to display no_post.html page ? I tried to filter at exists(), then it would display no_post.html properly, but wouldn't display 1) properly. How would I be able to make all 4 options work? -
Showing request.user rating for object in a list of objects
Models: class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey(Author, on_delete=models.CASCADE) published = models.DateField() genre = models.ManyToManyField(Genre) cover_art = models.ImageField( blank=False, default='/media/book-cover-placeholder.jpg') slug = models.SlugField(unique=True, blank=True) objects = models.Manager() class Meta: ordering = ['-published'] def get_absolute_url(self): return reverse("bookDetailsPage", kwargs={ 'slug': self.slug }) def __str__(self): return self.title class UserRatings(models.Model): RATINGS = [ (1, '1'), (2, '2'), (3, '3'), (4, '4'), (5, '5'), ] user = models.ForeignKey(User, on_delete=models.CASCADE) user_rating = models.IntegerField( validators=[MinValueValidator(0), MaxValueValidator(5)], choices=RATINGS, default=None) book = models.ForeignKey( Book, on_delete=models.CASCADE, blank=True, default=None, null=True) objects = models.Manager() def __str__(self): return self.title View: def homePage(request, id=id): qs = Book.objects.all().order_by('-published') paginator = Paginator(qs, ITEMS_PER_PAGE) page = request.GET.get('page', 1) qs = paginator.get_page(page) get_dict_copy = request.GET.copy() params = get_dict_copy.pop('page', True) and get_dict_copy.urlencode() context = { 'qs': qs, 'params': params, } return render(request, 'homePage.html', context) Template: <section class="container"> {% for book in qs %} <div class="image-container"> <a href='{{ book.get_absolute_url }}'> <img class="cover_art" src="{{ book.cover_art.url }}" title="{{ book.title }}" /> <div class="list_rating" id="list_rating_{{book.id}}"> <form action="{% url 'detailRatingRedirect' book.id %}" method="post"> {% csrf_token %} <span class="star-group"> <input type="radio" name="user_rating" id="user_rating_5_{{book.id}}" class="radio_input" value="5"> <label for="user_rating_5_{{book.id}}">5</label> <input type="radio" name="user_rating" id="user_rating_4_{{book.id}}" class="radio_input" value="4"> <label for="user_rating_4_{{book.id}}">4</label> <input type="radio" name="user_rating" id="user_rating_3_{{book.id}}" class="radio_input" value="3"> <label for="user_rating_3_{{book.id}}">3</label> <input type="radio" name="user_rating" id="user_rating_2_{{book.id}}" class="radio_input" value="2"> <label for="user_rating_2_{{book.id}}">2</label> <input type="radio" name="user_rating" … -
Django how to add @login_required error message
I'm using the @login_required decorator for my webapp and I've set it so that when a user tries to access the index without being logged in, he is redirected to the login page. I'd like to display an error message whenever the user is redirected to this login page. I've tried using the source code of the @login_decorator and creating my own with: def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None): """ Decorator for views that checks that the user is logged in, redirecting to the log-in page if necessary. """ actual_decorator = user_passes_test( lambda u: u.is_authenticated, login_url=login_url, redirect_field_name=redirect_field_name ) if function: messages.success(request, 'Error message here') return actual_decorator(function) return actual_decorator However this doesn't work. I've also tried multiple solutions which rely on available_attrs which is no longer supported by Django. Is there a way to solve this? Thanks in advance -
Creating models.UniqueConstraint in django, but the constraint is not applying
My table is defined as below. class Role(models.Model): user = models.ForeignKey( settings.AUTH_USER_MODEL, to_field="email", db_column="user", on_delete=models.CASCADE ) vertical = models.ForeignKey( Verticals, to_field="name", db_column="vertical", on_delete=models.CASCADE ) product_domain = models.ForeignKey( ProductDomains, to_field="name", db_column="product_domain", null=True, on_delete=models.CASCADE ) class Meta: constraints = [ models.UniqueConstraint(fields=[ 'user', 'vertical', 'product_domain' ], name='unique-permissions-per-user') ] Here the UniqueConstraint is not working, why? I use models.UniqueConstraint in the same project many times but it doesn't work in this case. My configuration is Django - 3.0.4 Django Rest Framework - 3.11.0 Database - MySql Please help and ask if any information is missing out. -
How to set data type of path parameter in drf-yasg
I use Django, the DRF, drf-yasg and Swagger Codegen to automatically build TypeScript code to access my REST API. In the Django backend I added a path to be served with the DRF: rest_router = routers.DefaultRouter() rest_router.register(r'source/(?P<source_id>[0-9]+)/document', DocumentViewSet) DocumentViewSet is a DRF ModelViewSet. As you can see, the source_id parameter is of numeric type. However, the resulting generated API description defines the source_id parameter as type String. Obviously the numeric regexp in the path setting is not enough so I guess I need some type annotation in the DocumentViewSet class? I tried the following code, but this showed no effect: @swagger_auto_schema( manual_parameters=[ openapi.Parameter(name="source_id", required=True, type="integer", in_="path", description="Source reference", ), ], ) class DocumentViewSet(viewsets.ModelViewSet): serializer_class = rest_serializers.DocumentSerializer queryset = models.Document.objects.all().order_by('id') How can I tell drf-yasg to set the source_id parameter to type Integer? -
removed column from postresql, but django doesn't see it
I removed the column from postresql database by using sql statement (alter table table_name drop column if exists column_name); It removed it... But django model doesn't see it... I tried "syncdb", but it is deprecated, so no more functional, tried makemigrations and migrate, but it doesn't change models in django... It should be quite simple task? Since it should be normal to change database (if not primary or foreign keys)... but nothing I tried works for me and there are seems no answer for this questions... fake migrations wouldn't be good for database, and turning off django changing database is not an option also? And because I have django and postresql not synced, I have filter fault which comes up... Any help? Thank you! -
Using Crispy Forms on Django how do I add an address field?
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm from .models import Profile class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = ('username', 'email', 'first_name', 'last_name', 'password1', 'password2', ) def save(self, commit=True): user = super(UserRegisterForm, self).save(commit=False) user.first_name = self.cleaned_data['first_name'] user.last_name = self.cleaned_data['last_name'] user.email = self.cleaned_data['email'] if commit: user.save() return user class UserUpdateForm(forms.ModelForm): email = forms.EmailField() class Meta: model = User fields = ['username', 'email'] class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['image'] -
Use the value of an input field in calculation, and display the result in another element
I have a shopping cart, with a price, quantity, and subtotal field for each product. The quantity field can be changed by the user, but the other fields are static. Is there a way to calculate the subtotal when the quantity is changed by the user? I want to multiply the quantity with the price, then update the subtotal, without the need for the user to submit the form. Also, when a subtotal is calculated, the total should be updated as well. Visual representation here My code is a Django template and looks like this, with the relevant part in the loop: <div class="container"> <table id="cart" class="table table-hover table-condensed"> <thead> <tr> <th style="width:50%">Product</th> <th style="width:10%">Price</th> <th style="width:8%">Quantity</th> <th style="width:22%" class="text-center">Subtotal</th> </tr> </thead> {% for crops_ordered_names,crops_ordered_images,crops_ordered_cost,crops_ava in total %} <tbody> <tr> <td data-th="Product"> <div class="row"> <div class="col-sm-2 hidden-xs"><img src="http://placehold.it/100x100" alt="..." class="img-responsive"/></div> <div class="col-sm-10"> <h4 class="nomargin">{{crops_ordered_names}}</h4> <p>Available amount: {{crops_ava}}</p> </div> </div> </td> <td data-th="Price" id="price">{{crops_ordered_cost}}</td> <td data-th="Quantity"> <input type="number" class="form-control text-center" id="quan" min="1" max="{{crops_ava}}"> </td> <td data-th="Subtotal" class="text-center" id="subtotal"></td> <td class="actions" data-th=""> <button class="btn btn-danger btn-sm"><i class="fa fa-trash-o"></i></button> </td> </tr> </tbody> {% endfor %} <tfoot> <tr class="visible-xs"> <td class="text-center"><strong>Total 1.99</strong></td> </tr> <tr> <td colspan="2" class="hidden-xs"></td> <td class="hidden-xs text-center" id="total"><strong>Total </strong></td> </tr> </tfoot> … -
Does Django have a built-in application for location awareness?
I will be asking users when signing up to provide their location. Does Django have a built-in application for this? If not, can anyone recommend a third-party package? The idea is for users to search for other users based on a certain mile range.