Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to handle granular permissions with django and django-sitetree?
I'm trying to build one central and easily maintainable place where we can manage access permissions for our homepages. Problem: django-sitetree comes with the function to associate to each tree item user groups with access permission. This only controls which sitetree items are getting displayed, everyone can still access any page by typing in the url though. If a user has no access to a top level sitetree item but to one of the children the toplevel doesn't show up. This only covers the views but not the apis. I'm aware there are a lot of permission packages out there but so far I only found some which require to define permissions per view which makes it very difficult to maintain and to keep track. Aim: Employees should be grouped. One central database table where one stores which group/s have permission to which sitetree element. Some process that associates a sitetree element with all attached views, apis and filterapis and secures their access as well. An interface to easily manage the permission: For example a vertical list of all sitetree elements and their children and next to them a MultiSelectDropdown for the groups, or a table with all sitetree elements … -
django: can we pass the session id though cookie in postman and get logged in
I am trying to create some api's for my application. I also have the normal website. I am not using any secure connection. Assuming i login into my normal website and then copy the session-id using inspect tools. and using postman set the cookie to the api and send the request, will the authentication middleware set the request.user based on the session-id -
how do I do compare between the value comes from methods and values in queryset? [django]
if I need to make a comparison between two values. the first value comes from (POST method) and the second value comes from list of queryset in the database of Django. for instance, answer = request.POST['answer'] suppose we have a class called (Result), in this case, (The Result) have some values in the list as a (queryset) that we need to compare with (answer). 1 - so, how we do this comparison if it is true? 2 - also, if that way not the correct way then what is the alternative way to make something like that? 3 - how can I do a comparison with string into a list of queryset, for instance, if answer in Result.objects.all() -
The Web browser am using can't display my application
I am new in Python and Django. Please I need your support.Here is my challenge. I created a project or site using "startapp polls" via the command prompt. In the polls' project I created a file called "url.py " inside of it,here is the code: from django.urls import path from . import views urlpatterns = [ path('', views.hello, name='hello'),] Here is the code inside of the "View file" from the "poll project" : from django.http import HttpResponse def hello(request): return HttpResponse("Hello, world. You're at the polls index.") then I point the function "hello" to the project called "myproject" that was created with "startproject in the url.py : from django.contrib import admin from django.urls import path,include urlpatterns = [path('polls/', include('polls.urls')),path('admin/', admin.site.urls),] Thereafter,I tried to launch it with this address ; "localhost:8000/polls/" the message I got was:"This site can’t be reached" my PC is already connected to internet. Please,how do I fix this problem? Thank you. -
Access fields Django admin in TabularInLine
I have a model with a ManyToMany relationship using a default through table: class Foo(models.Model): bool = models.BooleanField( default=True, ) bars = models.ManyToManyField( to='Bar', related_name='bars', ) class Bar(models.Model): bool = models.BooleanField( default=True, ) how do you access the field bools in Foo and Bar in a TabularInLine in the Django admin ie. class BarInline(admin.TabularInline): model = Foo.bars.through fields = [Foo.bool, Bar.bool, ] -
Model History Revert button remove in Django Admin
Revert button hide or remove How to hide this revert button or remove their functionally in model history in Django admin side But I do not change HTML template. only override the revert fun calling (_save fun call ) -
Is it possible to use `modelformset_factory` on an unmaanged database model?
I have an unmanaged model called Codemap class Codemap(models.Model): code_map_id = models.AutoField(primary_key=True) field = models.CharField(max_length=255, null=True, blank=True) class Meta: managed = False I just wanna know whether it's possible to use modelformset_factory here, cause using has_changed() raises an AttributeError forms.py class CodeMapFinal(ModelForm): def init(self, *args, **kwargs): super().init(*args, **kwargs) self.queryset = Codemap.objects.all() class Meta: model = Codemap fields = '__all__' views.py class CodeMapView(View): template_name = 'tabledata/code-map.html' def get(self, request): codemap = Codemap.objects.all() codemap_formset = modelformset_factory(Codemap, form=CodeMapFinal, can_delete=True, exclude=['code_map_id', 'display_label', 'type'], extra=0) return render(request, self.template_name, context={'rows': codemap, 'formset': codemap_formset}) def post(self, request): formset = CodeMapFinal(request.POST) if formset.is_valid(): instances = formset.save(commit=False) return HttpResponse("asdfasdfasdf") template.html <div class="row"> <div style='background-color: #f2f2f2;' class="col-2"> <strong>Type</strong> <ul> {% for row in rows %} <li><a href="#" onclick="show_type_specific({{row.code_map_id}})">{{row.type}}</a></li> {% endfor %} </ul> <strong>Display Label</strong> <ul> {% for row in rows %} <li><a href="#" onclick="show_display_specific({{row.code_map_id}})">{{row.display_label}}</a></li> {% endfor %} </ul> </div> <div class="w-100 col-4"> <table class="table table-bordered"> <tr> <th>Index</th> <th>Type</th> <th>Input Value</th> <th>Output Value</th> <th>Display Label</th> </tr> <tbody class='table-body'> {% for row in rows %} <tr> <td>{{forloop.counter}}</td> <td>{{row.type}}</td> <td>{{row.input_value}}</td> <td>{{row.output_value}}</td> <td>{{row.display_label}}</td> </tr> {% endfor %} </tbody> </table> </div> </div> <div id="form-div" hidden="hidden"> <h3>Code Map</h3> <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} <div id="form_set"> {% for form in formset %} {{form.non_field_errors}} … -
How to add new field to filtered query
I'm trying to add a new column for which I need to do some operations based on other models in a FilterSet. I have my view like this: class FilteredListView(ListView): filterset_class = None def get_queryset(self): queryset = super().get_queryset() self.filterset = self.filterset_class(self.request.GET, queryset=queryset) return self.filterset.qs.distinct() def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filterset'] = self.filterset querysetPaises = Pais.objects.all().filter(paisActivo=1).order_by('nombrePais') context['paises']=querysetPaises return context class ListadoPartnerView(FilteredListView): paginate_by = 10 model = IngresosPersonas fields = ['idPlataforma', 'number_plataforma', 'contactoinfo'] template_name = 'usuarios/listadoPartners.html' And my filter is: class PartnerFilter(django_filters.FilterSet): class Meta: model = IngresosPersonas fields = ['idPlataforma', 'number_plataforma'] Basically I want to include a new column on the filterset that the template receives which is not included in the model. I've tried to access the filterset.qs but no luck Many thanks -
Django get annotated model fields
I have two models Player and Game class Player(models.Model): userId = models.CharField(max_length = 150, primary_key=True) username = models.CharField(max_length = 250) email = models.CharField(max_length = 150) playedGames = models.IntegerField() class Game(models.Model): player = models.ForeignKey(Player, on_delete=models.CASCADE) date = models.DateTimeField() award = models.IntegerField() And I make request to get all players with their maximum awards. wins = Player.objects.annotate(maxAward=Max('game__award')).values().order_by('-maxAward') But also I want to show 'date' for all selected games (where award is maximum). How should I change my request? -
Django Model FileField storage use class depends on settings
I would like to manage django multimedia files locally and in the aws s3, I have all the configuration and if I specify the storage class in the model it works fine, but it is not practical because I have to do migrations every time, but I would like to establish that the File configuration depends on the configuration variable called 'FILES' to work programmatically. This is the code settings.py FILE_OVERWRITE = True if FILES == 'LOCAL': MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIAFILES_STORAGE = 'app.files.CustomStorage' MEDIA_URL = '/media/' elif FILES == 'AWS': MEDIAFILES_STORAGE = 'app.files.MediaStorage' MEDIA_URL='https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, MEDIA_LOCATION) storages.py class CustomStorage(FileSystemStorage): def get_available_name(self, name, *args, **kwargs): if self.exists(name): if settings.FILE_OVERWRITE: os.remove(os.path.join(settings.MEDIA_ROOT, name)) else: alternative_name = name.split('.') name = alternative_name[0] + str(timezone.now()).split(' ')[0] + '.' + alternative_name[1] return name class MediaStorage(S3Boto3Storage): location = settings.MEDIA_LOCATION file_overwrite = settings.FILE_OVERWRITE models.py class Bill(ChangesMixin, models.Model): #pdf = models.FileField(storage=CustomStorage(), upload_to='media/', blank=True, null=True) <-- on local with this class works well #pdf = models.FileField(storage=MediaStorage(), upload_to='media/', blank=True, null=True) <-- on aws with this class works well # throw an error because settings class name is not callable pdf = models.FileField(storage=settings.MEDIAFILES_STORAGE, upload_to='media/', blank=True, null=True) Anybody could help me ? How can I do this ? Thanks in advance. -
Create group when another model is created
I have a model workspace and and I use the model group from django to apply permissions. However, whenever an user create a workspace I want the workspace to create a group as well. This is what I tried : instance = form.save(commit=False) instance.token = uuid4() x = uuid4() groupworkspace = Group groupworkspace = Group.objects.create('GROUP TEST') instance.join_token = str(x)[:8] instance.join_token_date = datetime.now() instance.save() instance.members.set([request.user] Now everything work except that I does not create the group, instead it return. create() takes 1 positional argument but 2 were given Thanks for your help -
django store '' in not null fields instead of raising error
if I don't insert value to not null fields Django must raise error to me, but if I don't send any value to not null fields Django automatic store a '' in not null fields instead of raising errors this is my model class Project(models.Model): title = models.CharField(max_length=100) body = models.TextField() category = models.ForeignKey(Category, models.SET_NULL, null=True) expertises = models.ManyToManyField(Expertise) language = models.CharField(max_length=35) email = models.EmailField() attachments = ArrayField(models.FileField(), null=True, blank=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering = ['-created_at'] and this is code of creating object project = category.project_set.create( title="a title", body='a body text' ) -
How to combine date field and time field to store in datetime field in django api post request?
I am Posting date and time separately and trying to save it in my django datetime field. Here is my code , any help will be appreciated. views.py event = Event() start_date = request.POST['start_date'] start_time = request.POST['start_time'] event.start_timestamp = datetime.combine(start_date,start_time) event.save() -
Set the limit of a specific query set
i have an api view which returns some dropdown options. I am trying to set the queryset limit in order to avoid the pagination. I tried the follow but i get error: Cannot filter a query once a slice has been taken. . If i remove the [:100000] it is ok class TestViewSet( GenericViewSet, mixins.ListModelMixin, mixins.DestroyModelMixin, ): queryset = models.Test.objects.select_related('user').all() def get_queryset(self): base_qs = super(TestViewSet, self).get_queryset() if self.action == 'get_dropdown_options': base_qs = base_qs.filter( user_id=self.request.get_session()['user_id'] )[:100000] return base_qs -
Where to execute an external API call that fills Django Model information
Giving next Django model: class Expedition(models.Model): code = models.CharField(max_length=256, blank=True) order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='expeditions') I wish to expose an endpoint which will be used in the frontend in order to create an Expedition, but the code is retrieved from an external API call. I've tried to override the perform_create method in the ModelViewSet adding the external API call and then checking if response.status_code == 200 or not, but the serializer's create method is always called with code = ''. How can I manage the API call? -
How to run a function periodically in django/celery without having a worker (or using Schedule)?
I would like to run my function do_periodic_server_error_checking every ten minutes, but I do not wish to: have it run on a worker - I'd like it to be run on the server itself (as far as I can see there is no way to get apply_async, delay, or @periodic_task to run on the server) use Schedule - (not sure why people are recommending a busy-waiting approach for a django server - maybe I'm missing something about the operation of Schedule) My best idea so far is to schedule a cron job to make an HTTP request to the server, but I'm wondering if there's an easier way from within django itself? -
How to chek celery task is running or not from django templates
I need some help for implementing django celery properly Q1: Set custom id for celery task @shared_task def lazy_post_link_1_task(post_url, current_user, no_of_lazy_bot, no_of_comment_for_lazy_bot, lazy_bot_time_interval): instagram_bot = InstagramBot() lazy_bots = InstagramModel.objects.filter(Q(bot_type='lazy_bot') & Q(running_status='idle'))[ :int(no_of_lazy_bot)] for bot in lazy_bots: lazy_bot_filter_comments = Comments.objects.all().exclude(botscomment__bot_id=bot.id)[ :int(no_of_comment_for_lazy_bot)] instagram_bot.comment_on_post(post_url, current_user, bot.id, bot.email, bot.password, lazy_bot_time_interval, lazy_bot_filter_comments) Q2: How to check if this task is running or not from django templates and in from django view also for example if lazy_post_link_1_task.status == running: # do some stuff else: # do some stuff Q3: How to kill the task from django templates -
When exactly is Django2.2 View __init__() called? When are
the below is taken from the documentation of the generic class View's init method (django/views/generic/base.py): Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. If my two experimental views are subclassing View and some other non-view classes and the code looks like more or less like below. NB, the function func() has some important side-effects and I am interested WHEN and HOW OFTEN they are called. I only know that in case of MyView, the func will be called each time the class Parent IS DEFINED, in case of MyView2, each time Parent2 or MyView2 is CALLED. But I fail to grasp when does this (respectively) happen - i.g. on each import, just once, on running the application, each time the endpoint is hit. Could someone explain me a bit those two cases? :) class Parent: var = func() class MyView(View, Parent): #... some usual stuff here class Parent2: def __init__(self): self.var = func() class MyView2(View, Parent2): #... some usual staff here -
i am getting error while giving my ip and localhost name in postgres admin
i am getting error while giving my ip and localhost name in postgres admin, any help would be appreciated. i am getting error while giving my ip and localhost name in postgres admin, any help would be appreciated. you can take a look at my postgres sql admin image in below url, [img url]: https://i.stack.imgur.com/p5KFe.png DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'myproject', 'USER': 'myprojectuser', 'PASSWORD': 'fakepassword', 'HOST': 'localhost', 'PORT': '', } } -
Populating json from multiple django models
I have the following 2 Django models, Lessons and UserLessons. Lessons would be created by an admin and UserLessons is basically when a user is in progress with the Lesson or completed the Lesson, linked by a foreign key. UserLesson doesn't necessarily contain a Lesson entry, till the user actually starts with that specific one. As I'm building an API (with DRF), I need to list the full list of all Lessons - easy. LessonList = Lesson.objects.all().values('id', 'title') This returns [ { "id": 1, "title": "Lesson 1" }, { "id": 2, "title": "Lesson 2" }, { "id": 3, "title": "Lesson 3" } ] However, I need to be able to merge it with UserLesson (eg UserLessonList = UserLesson.objects.filter(user=request.user).values('id', 'lesson__id', 'completed') which currently returns [ { "id": 2, "lesson__id": 1, "completed": true }, { "id": 3, "lesson__id": 2, "completed": true } ] Ideally, it should return all the lessons from the db, and the the completed values, defaulting to completed: false if that specific lesson doesn't exist in DB. Any suggestions? -
How to make models of app available to other apps in a django project?
It seems like to be best practice (or at least one common way) to create a Django 3 based fullstack project which uses project specific Django apps (instead of standalone Django apps) with a structure like this (refer to e.g. here): fullstack_project/ frontend/ ... # frontend stuff goes into here backend/ # Django project name apps/ app1/ apps.py logic.py models.py ... app2/ apps.py logic.py models.py ... wsgi.py ... manage.py The apps (here: app1) are integrated in the most basic form (no ruls, views, etc.) via fullstack_project/backend/apps/app1/apps.py class App1Config(AppConfig): name = 'backend.apps.app1' and fullstack_project/backend/settings.py INSTALLED_APPS = [ ... 'backend.apps.app1.apps.App1Config', 'backend.apps.app2.apps.App2Config', ] Using logic of one app (e.g. app2/logic.py) in another app (e.g. app1/logic.py) works just fine (e.g. via from backend.apps.app2.logic import ... in app1/logic.py). However if I try to access the models of app1 in the logic of app2 I get django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.. I could implement a database wrapper for an app to allow cross-app database access. However ass the apps are cross-project anyway I'd like to avoid that and allow access more easily. How can I fix this issue? -
How is nginx paired with docker treating referenced files?
I am running a dockerized django app. I deployed it on EC2. Nginx is also in a docker container. Nginx in my docker-container is configured so that it uses ssl certificates from Lets Encrypt. Lets Encrypt certificates are only valid for 90 day, that's why I set a cronjob to renew them. My question now is: Will my nginx that runs in a docker container automatically use the updated file? Or do I need to spin up my docker container again and build it anew for the changes to take effect? In the latter case, is it possible to tell nginx to use the renewed file so I don't have to rebuild my container? I'm asking because I'd like to minimize downtime for my application. For more clarity I provide my config. The important files are the referenced ssl certificates: server { listen 443 ssl; server_name mydomain; charset utf-8; ssl_stapling off; ssl_stapling_verify off; ssl_certificate /etc/letsencrypt/live/mydomain/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/mydomain/privkey.pem; location / { proxy_pass http://django:5000; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } Here my compose file: production-nginx-container: container_name: 'production-nginx-container' image: nginx:latest ports: - "80:80" - "443:443" volumes: - /home/ubuntu/nginx-conf/myconf.conf:/etc/nginx/conf.d/default.conf - /etc/letsencrypt/live/mydomain/fullchain.pem:/etc/letsencrypt/live/mydomain/fullchain.pem - /etc/letsencrypt/live/mydomain/privkey.pem:/etc/letsencrypt/live/mydomain/privkey.pem depends_on: - django I can only see two options: … -
Getting an error when integrated django-private-chat in the django project?
I am working on an application where I want to implement the django-private-chat in for one to one messaging feature after I did everything which is said in the documentation I ran the server and got to the link http://127.0.0.1:8000/dialogs/ I am getting this error please help me out I have included the error traceback also -
How can I prevent Django app:ready() being called twice?
In my apps.py I have: import os # class ServerConfig(AppConfig): name = 'server' def ready(self): print("django started - start type: " + os.environ["DJANGO_START_TYPE"]) I run my server from inside a docker container with: sudo service rabbitmq-server start rabbitmqctl add_user bunny floatFlap1 rabbitmqctl add_vhost bunny_host rabbitmqctl set_permissions -p bunny_host bunny ".*" ".*" ".*" python3 manage.py runserver 0.0.0.0:8000 The output prints "django started - start type: server" twice. django started - start type: server <some other stuff> django started - start type: server <some other stuff> Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 24, 2020 - 11:01:47 Django version 2.2.7, using settings 'django_site.settings' Starting development server at http://0.0.0.0:8000/ Quit the server with CONTROL-C. I do not wish this to be run twice - what am I doing wrong? -
How to fix [Errno 20] Not a directory: '/app/myProjectManager/settings.py/staticfiles/staticfiles.json' Django
I am trying to deploy an project manager app to heroku. It's running working locally. I am following the tutorial https://www.codementor.io/@jamesezechukwu/how-to-deploy-django-app-on-heroku-dtsee04d4 to deploy me app. I don't know where is the error and how to fix so hope you can help. NotADirectoryError at /, saying [Errno 20] Not a directory: '/app/myProjectManager/settings.py/staticfiles/staticfiles.json' Here is some of my backend code: MIDDLEWARE = [ 'whitenoise.middleware.WhiteNoiseMiddleware', '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', ] # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/1.11/howto/static-files/ PROJECT_ROOT = os.path.join(os.path.abspath(__file__)) STATIC_ROOT = os.path.join(PROJECT_ROOT, 'staticfiles') STATIC_URL = '/static/' # Extra lookup directories for collectstatic to find static files STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, 'static'), ) # Add configuration for static files storage using whitenoise STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' import dj_database_url prod_db = dj_database_url.config(conn_max_age=500) DATABASES['default'].update(prod_db) I cannot link to the static file successfully. This is the error part of my html template code: Error during template rendering <link rel="stylesheet" type="text/css" href="{% static 'projectManager/style.css' %}" /> My views.py: def home(request): return render(request, 'projectManager/home.html', {'projects': Project.objects.all()}) My models.py: class Project(models.Model): title = models.CharField(max_length=100) date = models.DateTimeField(auto_now_add=timezone.now()) def __str__(self): return self.title