Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Editing is_staff permissions for Djnago admin panel
I want to edit the is_staff role permissions so that they are only capable of viewing the data on the admin panel and not making any changes, I want to give the support staff this role. I understand the is_staff has edit, add, delete and view permissions. How would I create a group so that I can add any new staff members to this group I am really new to django, so please explain in the simplest of manner -
Add Prometheus metrics outside manage.py - docker related
My manage.py looks like this: import os import sys from prometheus_client import start_http_server, Summary import random import time if __name__ == "__main__": os.environ.setdefault("DJANGO_SETTINGS_MODULE", "core.settings") s = Summary('request_latency_seconds', 'Description of summary') s.observe(4.7) # Observe 4.7 (seconds in this case) try: from django.core.management import execute_from_command_line except ImportError: # The above import may fail for some other reason. Ensure that the # issue is really that Django is missing to avoid masking other # exceptions on Python 2. try: import django except ImportError: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) raise execute_from_command_line(sys.argv) If I run my django app using docker, I am able to see added Summary metrics. However, if I try to run Django management command, created metric object will be not added to Prometheus. I am basically trying to add many metrics the same way I did it with Summary, but I dont want my exposed port to be stopped (if I run loop inside manage.py, it will stop)... ideally, if I would be able to run management command (I will exec to running container, and run command like "python … -
AttributeError: 'str' object has no attribute 'likes'
I am trying to get the count of likes related to post so I created the following in the Post Model: class Post(models.Model): title = models.CharField(max_length=100, unique=True) likes = models.IntegerField(default=0) I am already able to get the no. of likes but I am trying a different method, I am just trying to know how the method works. Here is the views where I try to add to it when a like is made def like_post(request): user = request.user post = request.POST.get('post_id') current_likes = post.likes <------------Error coming from here if request.method == 'POST': post_obj = Post.objects.get(id=post) if user in post_obj.liked.all(): post_obj.liked.remove(user) current_likes = current_likes - 1 else: post_obj.liked.add(user) current_likes = current_likes + 1 post.likes=current_likes post.save() like, created = Like.objects.get_or_create(user=user, post_id=post) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() context = { 'post': post, } return redirect('blog:post-detail', slug=post_obj.slug) The issue now is that I am receiving AttributeError at /blogs/like 'str' object has no attribute 'likes' I have tried to fix it but I don't know how. The source of error is highlighted here: current_likes = post.likes -
Should I rewrite my code to make use of through fields?
I built the models in my Django projects before learning about through fields, and now I realize I could have made use of them. I'm wondering what the benefits of using through fields are, and if I am missing out on them with my model structure: models.py (non-relevant fields removed) class Language(models.Model): name = models.CharField(max_length=255) class Collaborator(models.Model): name = models.CharField(max_length=255, blank=True) language = models.ManyToManyField(Language, verbose_name="languages", related_name='language_collaborator_languages', blank=True) class Item(models.Model): name = models.CharField(max_length=255, unique=True) language = models.ManyToManyField(Language, verbose_name="list of languages", related_name='language_item_language', blank=True) class Document(models.Model): name = models.CharField(max_length=255) language = models.ManyToManyField(Language, verbose_name="list of languages", related_name='language_document_language', blank=True) class Dialect(models.Model): document = models.ForeignKey('Document', related_name='document_dialect_document', on_delete=models.CASCADE, null=True, blank=True) item = models.ForeignKey('Item', related_name='item_dialect_item', on_delete=models.CASCADE, null=True, blank=True) collaborator = models.ForeignKey('Collaborator', related_name='collaborator_dialect_collaborator', on_delete=models.CASCADE, null=True, blank=True) language = models.ForeignKey('Language', related_name='language_dialect_language', on_delete=models.CASCADE) name = models.CharField(max_length=255) To describe the conceptual data model: each instance of Items, Documents, and Collaborators, can all have multiple languages, and for each instance of these relationships I specify a dialect with the Dialect model. I use get_or_create() in views.py to generate instances of Dialect, in which I define the language field and one of the item/document/collaborator fields. (Note: If you are familiar with languages/linguistics, you might point out that I could rename the Language model as … -
Weblate Permission denied. Unable to stat ... 403 Forbidden
https://docs.weblate.org/en/latest/admin/install.html#uwsgi I have been following the installation procedure to install Weblate on Ubuntu 18.04.04 LTS. I have installed all the dependencies, python 3.6, and also had to setup a system unit called `celery-weblate.service': [Unit] Description=Celery Service (Weblate) After=network.target [Service] Type=forking User=weblate Group=weblate EnvironmentFile=/etc/default/celery-weblate WorkingDirectory=/home/weblate-env RuntimeDirectory=celery RuntimeDirectoryPreserve=restart LogsDirectory=celery ExecStart=/bin/sh -c '${CELERY_BIN} multi start ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' ExecStop=/bin/sh -c '${CELERY_BIN} multi stopwait ${CELERYD_NODES} \ --pidfile=${CELERYD_PID_FILE}' ExecReload=/bin/sh -c '${CELERY_BIN} multi restart ${CELERYD_NODES} \ -A ${CELERY_APP} --pidfile=${CELERYD_PID_FILE} \ --logfile=${CELERYD_LOG_FILE} --loglevel=${CELERYD_LOG_LEVEL} ${CELERYD_OPTS}' [Install] WantedBy=multi-user.target I also had to setup a weblate file in /etc/default for variables that are used in the daemon: # Name of nodes to start CELERYD_NODES="celery notify memory backup translate" # Absolute or relative path to the 'celery' command: CELERY_BIN="/root/weblate-env/bin/celery" # App instance to use # comment out this line if you don't use an app CELERY_APP="weblate.utils" # Extra command-line arguments to the worker, # increase concurency if you get weblate.E019 CELERYD_OPTS="--beat:celery --queues:celery=celery --prefetch-multiplier:celery=4 \ --queues:notify=notify --prefetch-multiplier:notify=10 \ --queues:memory=memory --prefetch-multiplier:memory=10 \ --queues:translate=translate --prefetch-multiplier:translate=4 \ --concurrency:backup=1 --queues:backup=backup --prefetch-multiplier:backup=2" # Logging configuration # - %n will be replaced with the first part of the nodename. # - %I will be replaced with the current child process index # … -
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?