Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass the address.pk as a parameter after the form has been successfully submitted in a django form?
I created an address form in a Django project and I have also created an AddressDetailView in views.py. When a user successfully submits the address form, I want to redirect the user into the address_details.html by passing the address.pk as the parameter. But I don't know how to pass that parameter. I keep getting an error as shown belong and I don't know how to fix it. this is the models.py for the address model route_name = models.ForeignKey(Route, on_delete=models.CASCADE) name = models.CharField(max_length=30) city = models.ForeignKey(City, on_delete=models.SET_NULL, blank=True, null=True) area = models.ForeignKey(Area, on_delete=models.SET_NULL, blank=True, null=True) location = models.CharField(max_length=30, choices=LOCATION_CHOICES, default='NULL') username = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE) make_initial_location = models.BooleanField() def __str__(self): return self.name def get_absolute_url(self): return reverse('address-detail', kwargs={'pk': self.pk}) this is the Address form in forms.py: class Meta: model = Address fields = ['route_name','name', 'city','area','location','make_initial_location'] def form_valid(self, form): form.instance.username = self.request.user return super().form_valid(form) this is the Address creation view in views.py, this is where i wrote the code for redirecting to address-detail, it shows me that the error is in return redirect('address-detail') : @login_required def AddressCreateVeiw(request): form = AddressCreationForm() if request.method == 'POST': form = AddressCreationForm(request.POST) if form.is_valid(): form.save() messages.success(request, f'Your address has been successfully created!') return redirect('address-detail') return render(request, 'blog/address_form.html', {'form': … -
Editing comments from a post: NoReverseMatch while trying to edit comment of a post
I am quite new to Django and I am trying to edit the comments for a specific post. However, I am getting an error while running the code. My guess is that it has to do with the url path or the post_detail html file(I tried multiple ways on fixing it, but could not get it to work). NoReverseMatch at /post/3c6f50b5-195a-4868-8704-b50c7b127813/ Reverse for 'edit_comment' with arguments '(33,)' not found. 1 pattern(s) tried: ['post/(?P<pk>[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/comment/edit/$'] Models.py: class Post(models.Model): id = models.UUIDField( primary_key = True, default = uuid.uuid4, editable = False) ... class Comment(models.Model): post = models.ForeignKey( Post, on_delete=models.CASCADE, related_name='comments', ) comment = RichTextField() ... urls.py: urlpatterns = [ ... path('post/<uuid:pk>/comment/', AddCommentView.as_view(), name='add_comment'), path('post/<uuid:pk>/comment/edit/', EditCommentView.as_view(), name='edit_comment'), path('post/<uuid:pk>/comment/delete/',DeleteCommentView.as_view(), name='delete_comment'), ... ] views.py: class EditCommentView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): model = Comment form_class = EditCommentForm template_name='blog/edit_comment.html' login_url = 'account_login' def test_func(self): obj = self.get_object() return obj.author ==self.request.user class DeleteCommentView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Comment template_name = 'blog/delete_comment.html' fields= '__all__' success_url = reverse_lazy('blog_home') login_url = 'account_login' def test_func(self): obj = self.get_object() return obj.author == self.request.user def form_valid(self,form): form.instance.post_id = self.kwargs['pk'] form.instance.author = self.request.user return super().form_valid(form) forms.py: class EditCommentForm(forms.ModelForm): class Meta: model = Comment fields = ('comment',) widgets = { 'comment': forms.Textarea(attrs={'class': 'form-control'}), } post_detail.html: {% if not post.comments.all … -
Remove file from S3 Bucket django-storages
I have a Django app that I am hosting on Heroku and the media files are served from AWS. I have a model that looks like this: class MyModel(models.Model): name = models.CharField(max_length=100) image = models.ImageField(upload_to="images/") def __str__(self): return self.name And I use a function inside views.py to delete the instance of the image from the model AND the image from the server. def delete_single_image(image): if image.image: image.image.delete() image.delete() This was working when I run it locally, but it doesn't delete the image from the S3 bucket when I host it on heroku. What can I do to remove it from there also? -
Django: dynamically append query results to context inside of view
I need to access models' data associated with one particular model (let's say model1). What is frustrating is that my database structure does not contain foreign keys or things to easily relate to model1. The underlying issue is that I can't figure away to manually replace the append method to add value:key pairs into the context dictionary. Here is what I have so far: @method_decorator(login_required, name='dispatch') class PostDetailalerte_trend2(LoginRequiredMixin,APIView, tables.SingleTableMixin, ExportMixin): def get(self, request): queryset = trend2.objects.all().values('reference') queryset2 = {} queryset3 = {} print(queryset) for object in queryset: queryset2.append(old_year2.objects.filter(Id = object['reference']).values('Qm3', 'Qm2', 'Qm1')) queryset3.append(demand_planning2.objects.filter(Id= object['reference']).values('ltplus1')) return render(request, 'detailstocktrend2.html', {'queryset': queryset, 'queryset2': queryset2, 'queryset3':queryset3}) ##how to replace the not working APPEND method?/ I have seen several example recommanding to manuall create the keys, however this is not an option because I cannot know in advance how big the dict will be. Any help or any alternative way to do that is welcome -
Run a function in Django after loading views
I want to run a python function when the user clicks a button, but I don't wanna run it before loading the template. For example in views.py def index(request): return render(request, "some_html.html") in some_html.html <form method="post"> <input type="button" id="run-button" value="RUN" name="run-button"> </form> And then when the users clicks the button "RUN", I wanna run a function, let's say doSomethingCool, how would it be? I'm wondering if it'd be like this on views.py def index(request): return render(request, "some_html.html") def doSomethingCool(request): if request.method == "POST" and "run-button" in request.POST: print("Some cool stuff") doSometingCool(request) Any ideas? -
TemplateDoesNotExit post_list.html
I have stumbled upon a problem where it tries to look for a template I did not even indented it to. My html files name is home.html but it looks for post_list.html. Here are the few of the files: urls.py: from django.urls import path from . import views from .views import HomeView urlpatterns = [ #path('', views.home, name = "home") path('', HomeView.as_view(), name = "home"), ] views.py from django.shortcuts import render from django.views.generic import ListView, DetailView from .models import Post # Create your views here. #def home(request): # return render(request, 'home.html', {}) class HomeView(ListView): model = Post template_score = 'home.html' ] Here is the directory. The commented lines are the ones that works, but when I try the class HomeView it gives me error. Exception Type: TemplateDoesNotExist Exception Value: myblog/post_list.html -
Deny an access to edit/delete a post, if the currently logged in user is not the author of the post. Django REST + simpleJWT
How can i change my postDetails view, in order to allow only the author of the post (currently logged in user) the option of PUT and DELETE a post made by him? views.py @api_view(['GET', 'PUT', 'DELETE']) def postDetails(request, pk): try: post = Post.objects.get(pk=pk) except Post.DoesNotExist: return Response({'message': 'The post does not exist'}, status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = PostSerializer(post) return Response(serializer.data) elif request.method == 'PUT': postData = JSONParser().parse(request) serializer = PostSerializer(post, data=postData) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': post.delete() return Response({'message': 'post was deleted successfully!'}, status=status.HTTP_204_NO_CONTENT) serializers.py class PostSerializer(serializers.ModelSerializer): class Meta: model = Post fields = '__all__' models.py class Post(models.Model): post_author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='posts') post_title = models.CharField(max_length=200) post_body = models.TextField() created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def __str__(self): return self.post_title -
What is the best way to exclude object instances from a QuerySet in Django (filter() not an option in this case)?
Right now the best solution I can think of is to individually use queryset.exclude(pk=instance.pk) on specific instances. The scenario is that I need to filter a model queryset for a few fields but then also check to see if a date field matches a given value. Normally I would just filter for date=mydate but in my case I need to calculate the date first using a stored timezone in a different model (which is why it seems like I can't simply use a filter) Right now my code looks something like this: user_tracks = HabitTrack.objects.filter(user=user) filtered_user_tracks = user_tracks for t in user_tracks: if not HabitEvent.objects.filter(user=user, track=t, date_expected=t.get_timezone_corrected_datetime_now().date(), post__isnull=True).exists(): print("Excluding ", t.track_name, " with track specific time of ", t.get_timezone_corrected_datetime_now(), "from the list of options") filtered_user_tracks = filtered_user_tracks.exclude(pk=t.pk) else: print("Including ", t.track_name, " with track specific time of ", t.get_timezone_corrected_datetime_now(), "in the list of options") For context, this is a snippet from my ModelForm so that I can limit form choices to only options available to the user "today" where "today" is calculated based on the user's timezone. (This is also my first time asking a question on SO, so I will do my best to clean up my question if … -
Why does Django default password hashing algorithm use 216000 iterations?
Why does Django password hashing algorithm pbkdf2_sha256 use exactly 216000 iterations? Why no 200000 or 256000? Those numbers seem to be much more natural. -
How to show multiple fields within a row? (Django Admin)
I've been struggling with a situation in Django/Mysql. There is this column in a table that has a primary key and foreign key at the same time. This column has a one to many relation with an intermediary table. It's a list of states linked to plant species. Some species can be found in more than one state. Species (table 1) Columns: Species_id | specie_name Species_to_states (table 2) Columns: Species_id | State_id States (table 3) Columns: States_id, State_name Models.py (code below) class Listaflor(models.Model): especie = models.OneToOneField(Flora2Estado, models.DO_NOTHING, primary_key=True) class Flora2Estado(models.Model): estado = models.OneToOneField(Estados, models.DO_NOTHING, primary_key=True) especie = models.ForeignKey('Listaflor', models.DO_NOTHING) class Estados(models.Model): estado_id = models.AutoField(primary_key=True) estado_nome = models.CharField(max_length=100, blank=True, null=True) nome_abbr = models.CharField(max_length=2, blank=True, null=True) criadoem = models.DateTimeField(db_column='criadoEm') # Field name made lowercase. class Meta: managed = False db_table = 'estados' verbose_name = "Estados" verbose_name_plural = "Estado" def str(self): return self.estado_nome+ " (" + self.nome_abbr+")" The point is that only one object is being displayin django admin (check the image below). So i would like to show multiple fields within a row. Can someone help me with that? Thank you so much -
Django Counting related object with a certain condition
I have this model classes in my django app: class Ad(models.Model): ... class Click: time = models.DateTimeField(auto_now_add=True) ip = models.GenericIPAddressField() ad = models.ForeignKey( to=Ad, related_name='views', on_delete=CASCADE ) class View: time = models.DateTimeField(auto_now_add=True) ip = models.GenericIPAddressField() ad = models.ForeignKey( to=Ad, related_name='views', on_delete=CASCADE ) Assume I have a queryset of Ad objects. I want to annotate the count of clicks for each add that happened in hour 12 to 13 (We could use range look-up). First I did it like this: query.filter(clicks__time__hour__range=[12, 13]).annotate(views_count=Count('views',distinct=True), clicks_count=Count('clicks', distinct=True)) but those ads which don't have any clicks in that range will be omitted from the query this way but I need them to be present in the final query. Is there any proper way to do so maybe with Django Conditional Expressions? -
django how to use exists()
The django docs have the following: entry = Entry.objects.get(pk=123) if some_queryset.filter(pk=entry.pk).exists(): print("Entry contained in queryset") could someone explain how this works? does the first line have to be executed? can we just do: if some_queryset.filter(pk=123).exists(): print("Entry contained in queryset") I'm confused by what some_queryset is. -
django catching all URLS under a specific name
I'd like to have one entry under urls.py that'll catch all sub-folders in a URL starting with a particular folder, example in this instance: example: /business /business/one /business/one/two /business/one/two/three /business/one/two/three/four I want all those URLS to go a single view, where I can later determine how many levels of folders there are after /business/ and their names. -
Using django, how to send messages from the view.py to the page prior to the postback
In django, when the user submits, how do you send messages to display on the page prior to the postback return? I believe those messages will need to be sent to a separate page using iframe, since the initial page is waiting for a page return. view.py def post_info(): from django.contrib import messages messages.success(request, "Starting processes...") ... ... messages.success(request, "In progress...") ... ... messages.success(request, "Completed.") return HttpResponseRedirect(self.request.path_info) template1.html {% if messages %} <ul class="messages"> {% for message in messages %} <li {% if message.tags %} class=" {{ message.tags }} " {% endif %}> {{ message }} </li> {% endfor %} </ul> {% endif %} -
Scalable view/edit access for form fields across different user types
I have a form page in django that I am presenting to my users. This page has a number of form objects being rendered, both the root object and various inlineformsets for one-to-many fields. I'm using inlineformset_factories for the one-to-many fields. This works fine. The problem is that now I need to expand this page to handle 5 different types of users on the page. Each user has the ability to view and edit certain fields across these form objects. I know I could do this by creating a unique form and inlineformset_factory per user type, but I'm going to end up with like 20+ forms/factories per form page. Is there a better way to define this view/edit access? -
404 Error when saving imagefield in admin
I have my project on production, I get an error trying to upload image in admin panel. I have uploaded all my settings static and others needed. Page not found (404) Request Method: POST Request URL: https://reliancestandardtrust.com/admin/myapp/profile/add/ Raised by: django.contrib.admin.options.add_view The current path, myapp/profile/add/, didn't match any of these. settings static: STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = '/home/relipoqe/public_html/media' STATIC_ROOT = '/home/relipoqe/public_html/static' Root url: from django.conf import settings from django.contrib import admin from django.conf.urls.static import static from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('accounts/', include('allauth.urls')), path('', include('myapp.urls', namespace='site')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Myapp url: from django.urls import path from django.conf.urls import url from myapp.views import ( IndexView, ProfileView, ) app_name = 'myapp' urlpatterns = [ path('', IndexView, name='index'), path('secure/ibank/p/', ProfileView, name='profile'), ] Model: class Profile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,blank=True,null=True) profile_pic = models.ImageField() class Meta: verbose_name = 'Profile' verbose_name_plural = 'Profiles' ordering = ['-date'] '''Method to filter database results''' def __str__(self): return self.user.username Admin: from django.contrib import admin from .models import Profile class ProfileAdmin(admin.ModelAdmin): list_display = ( 'user', 'date', ) search_fields = ( 'user__username', ) admin.site.register(Profile, ProfileAdmin) -
<how to pass data from HTML/Javascript to be used in Django in Python and back
I'll Summarize the problem: = i'm a beginner at django, html, python, but i must find a way to do something because of my schools demo project. To give absolutely minimum of the problem: I have a variable in html/javascript which i want to get and process in Django/python. When i have processed info on django/python side, i want to be able to access it from a html/javascript pages. I have tried to look into different things like Ajax, jquery, but i just don't unserstand it and most tutorials and such get way too wide and complex to grab that one thing i need. Thanks for any help :) Yes , i have gone thorough stackoverflow similiar questions. -
Django DATETIME_FORMAT option documentation?
Is there any format documentation for the options available in Django's DATETIME_FORMAT setting? It doesn't appear to use the same options as the similarly named DATETIME_INPUT_FORMATS, and the official doc page lists no options other than the default string. I thought it was derived from the standard options in Python's strftime, and while it does indeed appear to be very similar, it's not identical. For example, "%M" in strftime denotes minute, but in DATETIME_FORMAT it denotes month. -
How to set up GKE configuration in a yml file for Django app?
I am following below doc in the link to deploy the django application in the google kubernested engine. Setting up your GKE configuration in a yml file In the step Setting up your GKE configuration, there is yml file called polls.yaml. Where should I find this file? If it is not existed yet, where should I create it and follow what template? -
Django: Retrieving the number of objects after applying distinct() method
I have a course model which looks like: class Course(models.Model): course_code = models.CharField(max_length=20) course_university = models.CharField(max_length=100) course_instructor = models.CharField(max_length=100) # lastname course_instructor_fn = models.CharField(max_length=100) # firstname """ More fields are here """ Now I have selected instructors for each university using: qs = Course.objects.filter(course_university__iexact=uni).order_by('course_instructor','course_instructor_fn','course_university').distinct('course_instructor','course_instructor_fn','course_university') My intention is to now count each the distinct course_code for each instructor using an aggregate Count() function: so I am trying to basically do: new_qs = Course.objects.filter(id__in=qs).annotate(course_count=Count('course_code', distinct=True).values_list('course_instructor_fn', 'course_instructor', 'course_count') However, currently, I only get 1 for user_count no matter how many courses each instructor has. My intention is to get the number of courses each instructor offers. How can I do this successfully? -
why is django app creating huge keys in redis
I am running django app (wagtail) in kubernetes cluster along with redis. These two pieces are connected by django-redis. This is how my backend configuration look { "BACKEND":"django_redis.cache.RedisCache", "LOCATION":"redis://redis-service:6379/0", "OPTIONS":{ "CLIENT_CLASS":"django_redis.client.DefaultClient", "CONNECTION_POOL_KWARGS":{ "max_connections":1000 } } } This works just fine. I can see keys getting created in redis and app is also blazing fast thanks to redis. Now real issue is every once in a while app slows down for some time. Upong investigation we found out the real issue is a key of size ~90 MB is created in redis. to process this key app takes some time and slows down. To put a comparison other keys are less than 1 MB always just 1 key gets randomly created on one type of endpoint but not always. I tried to check the contents of the key after unpickling and it is normal amounts of data just like other keys. but running redis-cli --bigkeys gives output something like this Biggest string found '":1:views.decorators.cache.cache_page.XXXXXXX.GET.9b37c27c4fc5f19eb59d8e8ba7e1999e.83bf0aec533965b875782854d37402b7.en-us.UTC"' has 90709641 bytes has someone seen similar issue? Anyway to debug the root cause. django-redis version "==4.12.1" wagtail version "==2.11.1" django version "==3.1.3" -
GET API showing KeyError in browser, but working in Postman
I have encountered a strange problem where the GET API that I created was working fine in Postman, but not working at that specific URL when entered in the browser. Here is what the input and output should look like as shown successfully in Postman: Trying API in Postman Here is what the error is showing on my browser: Error in browser I am also getting this error in React about CORS headers even though I have added in code to try to handle that issue: Error in React about CORS Here is the code in settings.py in Django: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'Prediction', 'rest_framework', 'corsheaders', ] MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] Here is the code in local_settings.py in Django: ######################################### ## IMPORT LOCAL SETTINGS ## ######################################### try: from .local_settings import * except ImportError: pass DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'postgres', 'USER': 'postgres', 'PASSWORD': 'postgres', 'HOST': '127.0.0.1', 'PORT': '5432', } } ################################################################# ## (CORS) Cross-Origin Resource Sharing Settings ## ################################################################# CORS_ORIGIN_ALLOW_ALL = True I also tried adding this code in index.js in React to handle the CORS headers problem but it didn't work: const express … -
Conditional formatting Datatables to specific values in specific columns
So I have the following template: <div class="table-responsive-sm" style="overflow:scroll"> <table class="table table-striped table-bordered table-hover" id="example"> <thead class="thead-dark"> <tr> <th colspan="12" scope="colgroup"></th> </tr> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> </tr> </tbody> <tfoot> <tr> <th>A</th> <th>B</th> <th>C</th> <th>D</th> <th>E</th> <th>F</th> <th>F</th> </tr> </tfoot> </table> </div> In columns C,D and E there are values displayed, being either: R, G, Y (red, green, yellow) I have the following script: <script> $(document).ready(function() { $('#example').DataTable( { initComplete: function () { this.api().columns().every( function () { var column = this; var select = $('<select><option value=""></option></select>') .appendTo( $(column.footer()).empty() ) .on( 'change', function () { var val = $.fn.dataTable.util.escapeRegex( $(this).val() ); column .search( val ? '^'+val+'$' : '', true, false ) .draw(); } ); column.data().unique().sort().each( function ( d, j ) { select.append( '<option value="'+d+'">'+d+'</option>' ) } ); } ); } } ); } ); What I would like to do is turn the colour in each cell of columns C,D and E corresponding to the value that is found in the respective cells (R=red, G=green, Y=yellow). I managed to make a working datatables by copying this script, but I have no clue how to implement the effective code that could make the table change the colours of the cell. … -
function in another file wont get mocked
I have this class in a file called local.py: def get_credentials(creds): data = creds return data class ClassA: def __init__(self): body = "not a json" self.credentials = get_credentials(body) def run(self): print(self.credentials) def main(): inst = ClassA() inst.run() if __name__ == "__main__": main() all it does is return the credentials passed to it. I want to mock the get_credentials function for which I have another file test_local.py: from local import ClassA import unittest from unittest.mock import patch def mock_get_credentials(creds): return "123" class NameTestCase(unittest.TestCase): patch('local.get_credessntials', new=mock_get_credentials("test")) def test_whatever(self): print("true") inst = ClassA() inst.run() self.assertEqual(1, 1) if __name__ == '__main__': unittest.main() The output I keep getting is this: true not a json . ---------------------------------------------------------------------- Ran 1 test in 0.000s OK The fact that it spits out "not a json" to me shows that it is not taking in the mocked value. I don't understand why it's doing this as I feel I have follow the documentation. Would appreciate some help with this as to why its not getting mocked. -
TypeError: Object of type 'User' is not JSON serializable. Why is this happening?
I'm trying to create a new user using DRF. The code actually creates the user but I get a 500 error saying that user is not JSON serializable. I would like to get rid of this error. Here are how my files look views.py class UserCreateAPIView(ModelViewSet): queryset = EndUser.objects.all() serializer_class = NewUserSerializer permission_classes = (AllowAny,) serializers.py class NewUserSerializer(serializers.ModelSerializer): class Meta: model = models.EndUser fields = ('id', 'first_name', 'last_name', 'email', 'title', 'user_type', 'packages', 'practice_area', 'office_phone', 'level', 'companies', 'country', 'password', 'firm', 'sectors', 'verticals', 'user_ptr') def save(self, *args, **kwargs): user = super().save(*args, **kwargs) user.set_password(user.password) user.save() urls.py router.register('new-user', views.UserCreateAPIView) Enduser inherits User. Would anyone have any ideas on how to fix this?