Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What is the best approach to attain multi-tenancy in Django?
I'm using django as an API server(using DRF) and admin dashboard with Postgres DB. The problem is I'll have multiple tenants and I want to follow a total separation of concern flow. Data from one tenant should not in any way be accessible to the other. Example Scenario: Say I have multiple Institutes as my clients and every institute will have all of their students onboarded on my platform. No institute should be able to access other's data. I can think of 2 approaches: 1. Extending ModelAdmin for Admin pages and for the APIs I can get the tenant associated to a particular user from the request. In this approach, I'll have to check for the tenant of a user in every modelAdmin class and get a filtered queryset in the def get_queryset() method def get_queryset(self, request): tenant = request.user.tenant # using related_name of foreignkey queryset = Course.objects.filter(tenant_id=tenant) And have to do this similarly in the list, create, update and destroy methods of the ModelViewSet class while creating APIs class CourseViewSet(viewsets.ModelViewSet): queryset = Course.objects.all() serializer_class = CourseSerializer permission_classes = (DjangoModelPermissions,) def list(self, request, *args, **kwargs): tenant = request.user.tenant queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(tenant__id=tenant) serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) … -
How do I ensure consistency with Django's password reset email function
I am trying to use Django's built in password reset email function. The emails get sent for some user accounts but not others. All other email sending functionality on my app works - so I guess my settings are correct. I read that the user account has to have a 'usable' password so I tried changing that and then testing the reset function and still the emails do not deliver. I tested the reset function in the django shell with: >>> send_mail('Test', 'Test','MY_FROM_EMAIL_ADDRESS',['MY_TO_EMAIL_ADDRESS'], fail_silently=False) 1 As you can see the output from the shell command suggests that the email was send, but it was not received. Any ideas what may be causing the inconsistencies? -
how can I get specific foreign key field related to other model in django?
models.py class Product(DateTimeModel): product_id = models.CharField(max_length=200) product_name = models.CharField(max_length=200) def __str__(self): return self.product_id class ProductVariantsManager(models.Manager): def colors(self): return super(ProductVariantsManager, self).filter(variant_type='Color', approval_status = "Approved") class ProductVariants(DateTimeModel): product_id = models.ForeignKey(Product, related_name="product_variants", null=True, on_delete=models.CASCADE) variant_type = models.ForeignKey(VariantsType, null=True, on_delete=models.CASCADE) variant_value = models.ForeignKey(VariantsValue, null=True, on_delete=models.CASCADE) approval_status = models.CharField(max_length=50,choices=PRODUCT_STATUS,default="Pending",null=True, blank=True) objects = ProductVariantsManager() def __str__(self): return str(self.item_num) HTML <select name="color" class="form-control col-7" required> {% for i in product_id.productvariants_set.colors %} <option selected value="{{ i.variant_value}}">{{ i.variant_value}}</option> {% endfor %} </select> The Product has saved multiple variants based on colors. Here I need to get the variants_value(black, brown, red..) for the specific product's have. I have gotten nothing with this query. is there Foreign key problem querying here? Need help to get this correctly. -
The columns of my table do not have the proper width when I use the scrollX in my datatable
I am loading my datatable with ajax but the data in the columns is not being arranged correctly. Attached my code and photos of the problem. datatable libraries <link rel="stylesheet" href="{% static 'lib/datatables-1.10.25/css/dataTables.bootstrap4.min.css' %}"/> <link rel="stylesheet" href="{% static 'lib/datatables-1.10.25/plugins/fixedcolumns-4.0.1/css/fixedColumns.bootstrap4.css' %}"/> <link rel="stylesheet" href="{% static 'lib/datatables-1.10.25/plugins/responsive-2.2.9/css/responsive.bootstrap4.min.css' %}"/> <script src="{% static 'lib/datatables-1.10.25/js/jquery.dataTables.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/js/dataTables.bootstrap4.min.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/plugins/responsive-2.2.9/js/dataTables.responsive.min.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/plugins/responsive-2.2.9/js/responsive.bootstrap4.min.js' %}"></script> <script src="{% static 'lib/datatables-1.10.25/plugins/fixedcolumns-4.0.1/js/fixedColumns.bootstrap4.js' %}"></script> my table in html <table style="width:100%" class="table table-bordered table-striped display nowrap" id="data"> <thead> <tr> <th>Número</th> <th>Fecha de registro</th> <th>Hora de registro</th> <th>Medio</th> <th>Referencia</th> <th>Proceso</th> <th>Parametros</th> <th>Respuesta</th> <th>Resuspensión</th> <th>Estado</th> </tr> </thead> <tbody> </tbody> </table> El code of my datatable tblSuspension = $('#data').DataTable({ destroy: true, deferRender: true, scrollX: true, fixedColumns: true, ajax: { url: pathname, type: 'POST', headers: { 'X-CSRFToken': csrftoken }, data: parameters, dataSrc: "", beforeSend: function () { loading_message('...'); }, complete: function () { $.LoadingOverlay("hide"); } }, columns: [ {data: "id"}, {data: "date_joined"}, {data: "time_joined"}, {data: "medium.name"}, {data: "reference"}, {data: "process.name"}, {data: "parameters"}, {data: "response"}, {data: "id"}, {data: "id"}, ], columnDefs: [ { targets: [-4], class: 'text-center', render: function (data, type, row) { return '<a class="btn btn-warning btn-xs btn-flat" rel="parameters"><i class="fas fa-align-justify"></i></a>'; } }, { targets: [-3], class: 'text-center', … -
Which timezone to use for all users aroung the world?
Right now I am using UTC as timezone. But I am staying in Bangladesh and It is ahead of 6 hours from server time. I am using a clock as UTC timezone it is also showing me time ahead of 6 hours. <Clock format={'HH:mm:ss'} ticking={true} timezone={'UTC'} /> Here, I want global timezone. I am in Bangladesh so I will see the bd time, if I am in Russia, then I will see time according to russia. so which timezone to use for that? -
Django Channels and Accessing Models
I am running Django 3.2.10 and I am using Django Channels with daphne and gunicorn. I can get my websocket code to run and function without issue but when I go to access any of my django models I hit a snag. I'm doing something like this: async def receive(self): modelselected = await database_sync_to_async(self.get_model)() def get_model(self): return MyModel.objects.all()[0] When I do this which is what the official docs suggest I do, I get the following error from daphne: daphne | ERROR Exception inside application: could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"? My Django application works perfectly fine and I connect to the database no problem. I am at a loss to what I'm doing wrong. And my Postgres is running on Port 5432. Any thoughts? -
Django: Computing new attribute before serving data as GeoJSON
I have a dataset of point locations (in this example, schools). Before serving this data as GeoJSON, I'd like to compute polygonal buffers around the points, and add those as an attribute. I know that I can use django.core.serializers.serialize to convert a QuerySet into the GeoJSON format that I need. I also know how to calculate the buffer (self.geometry.buffer), I just can't figure out how to string this all together. models.py from django.contrib.gis.db import models class School(models.Model): name = models.CharField(max_length=50) geometry = models.PointField() def compute_buffer(self, radius): self.buffer = self.geometry.buffer(radius) views.py from django.core.serializers import serialize def data(request): geom_as_geojson = serialize('geojson', School.objects.all()) return HttpResponse(geom_as_geojson, content_type='json') -
How to update django local cache every day using django background tasks?
I'm using django local cache in my application. There is a certain table in my database which is used in high frequency, e.g. fetch top 10 records from a specific table. So, every time this runs a query in my DB to get this data. Also, I'm using django background tasks which updates this table every day. So, this top 10 records of the table will remain the same for a day and I want to keep this in some local cache so that it can be fetched directly from the local cache instead of running another query. I want to implement something like below, the refreshCache function should update the cache. But how to trigger it at certain time with django background tasks so that the cache gets updated in django server too? [Background task runs in a separate thread and triggered manually using python manage.py process_tasks] from django.core.cache import cache def refreshCache(): cache.set("TOP_10_RECORDS", MY_TABLE.objects.all()[:10]) Any alternative of the above solution is welcome! -
How can I join two model in django
I want to join two model. I am using postgresql. But the problem is I am not using any foreign key or many to field. But I am using same unique field for both table. So I want depends on thats field I can query from both table. "invoice" is the field. My models are class Salesinvoice(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) customer = models.CharField(max_length=100) product_name = models.CharField(max_length=80) price = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) quantity = models.IntegerField(default=0) class Salespayment(models.Model): id = models.AutoField(primary_key=True) date = models.DateField(default=date.today) invoice = models.CharField(max_length=20) amount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) discount = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) payment = models.DecimalField(max_digits=9, decimal_places=2, default=0.00) What should be my Views for join above both table depends on invoice field. -
What is the best way to add a field from a non-related model to a serializer in drf? I can't change the db. SerializerMethod field created n+1 queries
I have two models. Model A and Model B. Both are related to each other however there is no relation at the model level. I can't make the changes to the models either because of the nature of my project. I need to add the related fields of Model B in the serializer of Model A. What is the best way to achieve this? When I tried using serializer method field I ran into the n+1 query problem. -
How to use make delete request of generic viewset without sending the pk
I am using django in the backend and react native in the frontend, I have a generic viewset with destroy, create mixins. In my use case, I make a post request when the user is logged in and then delete the same instance when he logged out. The problem is I don't know the pk of the created instance to send it in the delete request. Is there a way to know the pk of the created model instance to use it then in the delete request? NB: the model pk is automatically generated in Django, not a created field. The view is class DeviceViewSet(mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): serializer_class = DeviceSerializer queryset = Device.objects.all() -
Video upload and view in different resolution in django
I am building a video streaming app like youtube in django for learning purposes. I want to implement the functionality of uploading video by user and view it in different resolutions like 360p, 480p etc. I dont know how to achieve this.. Should I save all the versions of video?? Wouldn't that be redundant?? Also how to convert the video in different resolutions! I want to use aws s3 for this. -
django-rest-framework: invalid regular expression in url_path
I have a view and action defined in it: class V(mixins.UpdateModelMixin, GenericViewSet): `` some codes`` lookup_field = 'uuid' @action(detail=True, methods=['put'], permission_classes=[IsAdminUser], url_path='approve/(?P<uuid>[\w-]+)') def approve(self, request, *args, **kwargs): obj = self.get_object() `` some codes `` The app doesn't run because of: django.core.exceptions.ImproperlyConfigured: "^url/(?P[^/.]+)/approve/(?P[\w-]+)/$" is not a valid regular expression: redefinition of group name 'uuid' as group 2; was group 1 at position 46 The correct configuration would be like ^url/approve/(?P<uuid>[\w-]+)/$, but as the error says, it's another pattern and I don't mean it. Any idea would be appreciated -
Django - Different user types with different registrations
I need to create two (and later more) user types: Individuals and Companies. When a user registers, they need to select what type they are. Depending on that, they need to fill in different forms based on each type's attributes, and later have different permissions. What I have tried so far is extending the AbstractUser model to include booleans for each user type: class User(AbstractUser): email = models.EmailField(unique=True) is_individual = models.BooleanField(default=False) is_company = models.BooleanField(default=False) Then I created two extra "Profile" models: class Company(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='company_profile') company_name = models.CharField(max_length=100, null=False, blank=True, help_text="Company name.") contact_email = models.EmailField(null=True,blank=True) def save(self, *args, **kwargs): super(Company, self).save(*args, **kwargs) class Individual(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='individual_profile') first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) avatar = models.ImageField(null=True) def save(self, *args, **kwargs): super(Individual, self).save(*args, **kwargs) I also set up signals to automatically create the profile when a user is created: @receiver(post_save, sender=User) def create_company_profile(sender, instance, created, **kwargs): if instance.is_company: if created: Company.objects.create(user=instance) elif instance.is_individual: if created: Individual.objects.create(user=instance) else: pass @receiver(post_save, sender=User) def save_company_profile(sender, instance, **kwargs): if instance.is_company: instance.company_profile.save() elif instance.is_individual: instance.individual_profile.save() else: pass This works when I add a user via Django Admin. If I tick is_individual, the an individual is added to the Individuals … -
500 (Internal Server Error) and Unexpected token < in JSON at position 0
I'm trying to create a website based on guides. When it came to updating the basket through the buttons (decrease and increase), then trying to click on them, errors are issued: Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0, which refers to .then((data) => { location.reload() }); cart.js:24 POST http://127.0.0.1:8000/update_item/ 500 (Internal Server Error) which refers to fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, and i have error in console pycharm line 104, in updateItem productId = data['productId'] KeyError: 'productId' code cart.js: var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function () { var productId = this.dataset.stuff var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) if (user == 'AnonymousUser') { console.log('User is not authenticated') } else { updateUserOrder(productId, action) } }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken': csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) customer = request.user.customer product = Stuff.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer, complete=False) orderItem, created = … -
How to cache data in django channels and celery?
I am building a web-app using django channels. I also have a task function which i run periodically ( every 30s) using celery beat. This task function sends data to my web-socket every 30s. Now, if a consumer joins my channel group, he has to wait for some time until my next data arrives. But what I want is to show the new consumer my previous data, until new one arrives. So i have to cache my previous data somewhere. What is the correct way to do that? I know using redis but how in django-channels? -
how to add an integer to current month and then update datefield in django
I am just trying to get the current month and then add an integer to it for example 3 months, then update my datefield obj to that value. my view.py : def worklist(request,pk): vessel_id = Vessel.objects.get(id=pk) vessel = Vessel.objects.all() component = vessel_id.components.all() components = component.prefetch_related( 'jobs').filter(jobs__isnull=False) if request.method == 'POST' and 'form-execute' in request.POST: this_job = Job.objects.get(pk=request.POST.get('execute_job_id')) job_type = this_job.type job_due_date=this_job.due_date job_interval =this_job.interval dt = datetime.datetime.today().month if job_type =='O': this_job.delete() else: job_due_date = dt + relativedelta(months=job_interval) return HttpResponseRedirect(request.path_info) context = {"component": components,"vessel_id":vessel_id,"vessel":vessel } return render(request, "worklist.html", context) i just want say thisjob due date equal to this month plus this job interval which is an integer here is model.py if it helps : class Job(models.Model): job_type = ( ('I', 'Interval'), ('O', 'One time'), ) name = models.CharField(max_length=100) description = models.CharField(max_length=100) type = models.CharField(max_length=1, choices=job_type) interval = models.IntegerField() is_critical = models.BooleanField() due_date = models.DateField() rank = models.ManyToManyField(UserRank,related_name='jRank') component = models.ForeignKey( Component, related_name='jobs', on_delete=models.CASCADE) runninghours = models.ForeignKey( RunningHours, related_name="RHjobs", on_delete=models.CASCADE,blank=True) def __str__(self): return self.name -
How to add points to an IntegerFiedl with serializer DRF
I've got serializer like this and each time i do Put on that url, i want the number_of_points increase(+=1), but now when i do it, it stays the same and doesnt change. Do you have any idea how to fix it? class Answer(models.Model): number_of_points = models.IntegerField(default=0) class AddPointsSerializer(serializers.ModelSerializer): class Meta: model = Answer fields = ('number_of_points',) def update(self, instance, validated_data): instance.number_of_points += 1 return instance class AddPointsAnswer(generics.UpdateAPIView): queryset = Answer.objects.all() serializer_class = AddPointsSerializer def get_queryset(self): return super().get_queryset().filter( id=self.kwargs['pk'] ) path('answers/<int:pk>/addpoints', AddPointsAnswer.as_view()), -
Custom user model with python-social-auth on django
I am new to this so sorry if what I am asking sounds silly. I am using only steamopenid on python-social-auth for the login, that's the only option the customer will have. Now I want to create my own custom user model where I can keep the user data once they log in. I believe it should not be too complicated but I can't find anything that seems correct. I have managed to get username but I want to also get everything that's under user social auths table and users table. The fields that are saved into python-social-auth generated table: settings.py SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.social_auth.associate_by_email', 'social_core.pipeline.user.create_user', 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', 'main.pipeline.save_profile', ) pipeline.py from .models import CustomUser def save_profile(backend, user, response, *args, **kwargs): CustomUser.objects.create( user = user, ) models.py from django.db import models from django.conf import settings # Create your models here. class CustomUser(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) -
Django model querryset changed into json serializable not working
I have model objects saved in session as below from context-processors. students = Student.objects.all() studente = serializers.serialize('json', students) request.session['students'] = students In my model Forms I have class NewIssueForm(forms.ModelForm): def __init__(self,*arg,students, **kwargs): super(NewIssueForm, self).__init__(*args, **kwargs) self.fields['borrower_id'] = students I get an error when I try to run. ''''' File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 994, in render return render_value_in_context(output, context) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\template\base.py", line 973, in render_value_in_context value = str(value) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\utils\html.py", line 376, in <lambda> klass.__str__ = lambda self: mark_safe(klass_str(self)) File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 132, in __str__ return self.as_table() File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 270, in as_table return self._html_output( File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 198, in _html_output bf = self[name] File "C:\Users\Ptar\AppData\Local\Programs\Python\Python39\lib\site-packages\django\forms\forms.py", line 163, in __getitem__ self._bound_fields_cache[name] = field.get_bound_field(self, name) AttributeError: 'str' object has no attribute 'get_bound_field' How can I make this field populate the students itemswithout the error? -
Django: packaging an app with a ForeignKey to settings.AUTH_USER_MODEL
I have an app that I use in many of my projects and want to package it. A model in the app has ForeignKey and ManyToManyField to settings.AUTH_USER_MODEL class LogEntry(models.Model): authenticated_user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='log_entries', on_delete=models.CASCADE) involved_users = models.ManyToManyField(to=settings.AUTH_USER_MODEL, blank=True, through='LogUsers', related_name='other_log_entries') migrations of this app in different projects refer to different user models. Sometimes a custom user model ('user', ... to='registry.RdpUser) other times the standard django.contrib.auth.models.User. Is it possibile to package the app with a migrations that works for both cases? What's the best approach for a packaged app with a ForeignKey to settings.AUTH_USER_MODEL? I know a solution would be to use GenericForeignKey but I would like to avoid that. -
Django form: ¿How can I wrap checkbox widget and label within a div?
¿How can I wrap checkbox and label in django form? I have django form with a BooleanField. That field renders like this: <div id="..." class="custom-control custom-checkbox" style=""> <input type="checkbox"....> <label for="...."....> <div> help_text <div> </div> I want to wrap the input and the label but not the help text: I want something like: <div id="..." class="custom-control custom-checkbox" style=""> <div id="wrapper_div"> <input type="checkbox"....> <label for="...."....> </div> <div> help_text <div> </div> -
how to setup django ssl for development purpose?
One notice: I'm new to python but was able to run django based project for mobile. There's a js part where I need to add some functionality about camera and what I found the web page needs to be run from https:// as I need access from my phone. Is running nginx with self signed cert the best solution? Will it working using https://192.168.0.xxx? -
why does clean_password2() method work but not clean_password1() in Django usercreationform
I am trying to figure out why this works if someone could maybe explain it to me. I've just created a custom user model (shown below) and for the password validation it uses the clean_password2(self): (shown below) method however when I try to use clean_password1(self): (shown below) the validation does not work. why? Surely using either password1 or password2 to clean the data would work since they are the same? Django docs state that we can use clean_<fieldname>(): methods to clean/validate data and since password1 is a fieldname in my mind that should work. Custom user model class UserManager(BaseUserManager): def create_user(self, email, password=None): if not email: raise ValueError("Users must have an email address") user = self.model(email=self.normalize_email(email)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password=None): user = self.create_user(email=email, password=password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class User(AbstractBaseUser): first_name = models.CharField(max_length=255) last_name = models.CharField(max_length=255) email = models.EmailField(verbose_name="Email Address", max_length=255, unique=True) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = [] def __str__(self): return self.email def has_perm(self, perm, obj=None): return True def has_module_perms(self, app_label): return True This works class UserCreationForm(forms.ModelForm): password1 = forms.CharField( label="Password", help_text=password_validation.password_validators_help_text_html(), widget=forms.PasswordInput, ) password2 = forms.CharField( label="Confirm Password", … -
Django project is not reading my static css file
I am working on a django project and for some reason the style.css file is not read. However, my static images are working. Not really sure what the issue is, any help is greatly appreciated. There are also no errors showing in the console and terminal.. Link to my github repository https://github.com/Amanuel763/petwebsite