Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to redirect from a Django View to some other view
For example if I have a view where I do some conversion according to the text-box input. Then I want to redirect to somewhere after the conversion is done, where the user can see the results. def main(){ //Some Conversion going on // After the conversion is done redirect to somewhere else if(conversion == done): return redirect('/somewhere') return render('index.html') } -
Efficiently update multiple fields in Django
Django beginner here. I have a many-to-many model and want to update multiple values at once. This is the model (simplified): class Inventory(models.Model): item = models.ForeignKey(Items, models.CASCADE) player = models.ForeignKey(Players, models.CASCADE) count = models.PositiveIntegerField() What I do right now is this: for key in dict: change_value = Inventory.objects.get(player=player, item=key) change_value.count += dict[key] change_value.save() At least on my HDD test environment this is very slow. Is there a more efficient way of doing this? In other posts it was suggested to use update instead, so this would be: for key in dict: Inventory.objects.get(player=player, item=key).update(count=dict[key]) Would this be faster? Could this be improved even further by updating multiple entries at once? Also, is there an efficient way of adding multiple new entries? -
How to override river-admin template?
Firstly , i would like to say that this package is amazing in the sense where there can be so much flexibility. Im relatively new to this package and im just trying to figure a way to fiddle around with the provided front end in the river-admin package. Could someone point me in the correct direction in doing so? -
Django, environment variables. Error: SMTPRecipientsRefused at /password_reset/
it's my first post here. I'm learning Django, and i'm trying to send an email to reset my password. There is one problem.. When I send an email with my username and password assigned to these constants, everything works well: EMAIL_HOST_USER = 'abc.def@gmail.com' EMAIL_HOST_PASSWORD = 'Abc123' But when i try to use environment variables instead: EMAIL_HOST_USER = os.environ.get('EMAIL_USER') EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASS') i got an error SMTPRecipientsRefused at /password_reset/ {'abc.def@gmail.com': (501, b': sender address must contain a domain')} Am I doing something wrong? Maybe I should use environment variables in different ways? In advance, thanks for your help, guys! -
can we work with Django authentication without builtin Django forms
I want to use input field for authentication but if I search for authentication tutorial they are using built-in Django forms which I can't design it using html -
how to implement a movie review system using sentimental analysis in python using django
Take a movie as a input from a user and pass it as a argument to our python file and our program will do a sentimental analysis on movie comments and give output wheather a movie is worth watching or not . framework used is django , backend language python and movie reviews collected from rottentomatoes. -
How to specify basehref in Django
Is it possible to launch Django app depending on .env configuration with BASEPATH=/api or just BASEPATH=/?