Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Recursive Foreign Key for Serializer Getting not iterable errors
I followed a lot of answers regarding my questions, I tried all solutions given here Basically scenario is almost same I wanted recursive query in my serializer. Firstly I want to show my models class Policy(TimeStampedModel): product = models.ForeignKey(Product, related_name='policies', on_delete=models.PROTECT, null=True) name = models.CharField(max_length=32) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify) and I have Foreign Key from Policy to PolicyCondition here is policy condition model. class PolicyCondition(TimeStampedModel): policy = models.ForeignKey(Policy, on_delete=models.CASCADE) name = models.CharField(max_length=200) slug = AutoSlugField(populate_from='name', editable=True, slugify_function=slugify,null=True) text = models.TextField() parent = models.ForeignKey( 'self', on_delete=models.CASCADE, null=True, blank=True, related_name='children' ) On serializer I am fetching all my data from policy model. Here is my serializer. class PolicyListSerializer(serializers.ModelSerializer): conditions = PolicyConditionSerializer(source='policycondition_set', many=True) class Meta: model = Policy fields = ['conditions'] Here is my policy condition serializer class PolicyConditionSerializer(serializers.ModelSerializer): class Meta: model = PolicyCondition fields = [ 'id', 'policy', 'name', 'text', 'slug', 'parent' ] def to_representation(self, instance): self.fields['parent'] = PolicyConditionSerializer(read_only=True) return super(PolicyConditionSerializer, self).to_representation(instance) I am getting error as PolicyCondition' object is not iterable any soluton what I am missing here. -
is there's a better way than saving user data in session?
When the user register and he enter his phone number, i don't save the data into the database untill the user verify his phone number by entering the code sent to his phone (OTP) the problem is that i save this data in the session untill he enter the OTP, then i save it into the DB is there's a better way? As it's not safe to save the user password in the session i thought about saving directly in the DB and i will use Corns.py to check every day if there's any user didn't verify his phone number, then it will delete it.. i also thought about saving normal info in the session like name, phone number, email, then i'll send him the OTP and after, he will continue registeration and he will type his password and it will be saved in the DB directly But i still think that there's a better solution what can it be? -
Empty fields on update commands
When using an update command there is no way to validate when a field is None by default or None due to a new value. Thanks in advance in you can help :) # views.py class UpdateCustomerView(APIErrorsMixin, APIView): class InputSerializer(serializers.Serializer): name = serializers.CharField(required=False) password = serializers.CharField(required=False) document = serializers.CharField(required=False) def put(self, request, id): input_serializer = self.InputSerializer(data=request.data) input_serializer.is_valid(raise_exception=True) cmd = commands.UpdateCustomer(id=id, **input_serializer.validated_data) bus = bootstrap.bootstrap() bus.handle(cmd) return Response(status=status.HTTP_204_NO_CONTENT) # commands.py @dataclass class UpdateCustomer(Command): id: UUID document: Optional[str] = None name: Optional[str] = None # handlers.py def update_customer( cmd: commands.UpdateCustomer, uow: AbstractCustomerUnitOfWork ) -> None: # So here comes the issue cmd.name is None because the view didn't receive it or because the dataclass of the command set its value to default? -
PyPi does not grab templates directory on a Django app
What is my goal I want to publish a PyPI package where the code within this package will be a Django application (migrations + templates folder, views, models, etc...) I created the project with setup.py which includes the necessary data so that the build module of python will build the PyPI package smoothly, with version management. This is the repository for further look: github-repo What is the problem The python -m build command does not take the templates directory within the package. It leads to a broken package of a Django application, because when you attempt to install the (package), it does not bring the templates. It is testable with pip install rlocker-expiryaddon What did I try I know that mentioning a file inside MANIFEST.in will be responsible to grab the files in the build process. (?) So I tried to inject the following line: recursive-include templates *.html schema.js Yet, no luck. I know that there are a lot of open-source libraries like the djangorestframework that is easy downloadable via pip and it brings it's templates directory to the system interpreter as expected. But for me, I am not sure what is wrong. Thanks for your help! -
Why Django admin custom modelform field is not saving data
I've got 2 models: Room and Roomgroup. My goal is to represent models in admin in both ways - Roomgroup in Room admin and Rooms in Roomgroup admin so I tweaked Roomgroup admin modelform in AdminModelforms but it's not working as I expected and I'd like to know where am I doing things wrong. And do I overcomplicate it? When I save Roomgroup in admin, it doesn't save roomgroup instance to Room model even for a new Roomgroup instance even for an existing one, it seems like data is cleared before save(). What's wrong? Models examples here are shortened but it correlates with my code. models.py: class Room(models.Model): name = models.CharField(max_length=200, verbose_name=_('Name'), unique=True, null=False) roomgroup = models.ForeignKey(Roomgroup, on_delete=models.SET_NULL, verbose_name=_('Room group'), null=True, blank=True) class Roomgroup(models.Model): name = models.CharField(max_length=200, verbose_name=_('Name'), unique=True, null=False) admin_forms.py: class RoomgroupAdminForm(forms.ModelForm): rooms = forms.ModelMultipleChoiceField( Room.objects.all(), widget=FilteredSelectMultiple(verbose_name=_('Rooms'), is_stacked=False), required=False, ) def __init__(self, *args, **kwargs): super(RoomgroupAdminForm, self).__init__(*args, **kwargs) # show just rooms without group self.fields['rooms'].queryset = Room.objects.filter(roomgroup=None) if self.instance.pk: # show rooms without roomgroup and the ones already assigned to this roomgroup self.fields['rooms'].queryset = Room.objects.filter(roomgroup=None) | Room.objects.filter(roomgroup=self.instance) # preselect rooms already assigned for the roomgroup self.initial['rooms'] = self.instance.room_set.all() def save(self, commit=True): instance = super(RoomgroupAdminForm, self).save(commit=False) if not instance.pk: for room … -
how to automatically reload Django project when backend files updated?
I have a Django rest project that its view reads from output a Matlab code. my file, 'output. mat' is updated at such times of the day; But when I make a request, Django does not show the expected values. my Django project does not show my updated value. I have to manually run 'python manage.py runserver' in the terminal to Django show the updated files (expected values). There is an idea to reload Django automatically when the Matlab outputs files are changed?? -
problem with exporting items from current formset(s) in Django 3.2
I have a view where the user inserts a number of units and once submit button is clicked the excel file is exported as xlsx file. I am using Django import-export to do that BUT I don't know how to filter the CERequests model so the user sees only what (s)he has just inserted. I have implemented the filtering by the user but when clicking submits button it filters all items by the current user but it shows all of them (also items from the past). What I want is to export only values from the current formset or formsets. What I tried is to put created=created in filter method but it gives me an empty Excel file. When I remove it gives me a list of all CERquests that the user inserted. What do I need to do to get only data from the current formset(s)? views.py class CostCalculator(LoginRequiredMixin, TemplateView): template_name = 'calculator/cost_calculator.html' def get(self, *args, **kwargs): # Create an instance of the formset formset = CalculatorForm(initial=[{ 'author': self.request.user.email, }]) return self.render_to_response({'ce_request_formset': formset}) # Define method to handle POST request def post(self, *args, **kwargs): formset = CalculatorForm(data=self.request.POST) # Check if submitted forms are valid if formset.is_valid(): for form in … -
How to replace ID in one table with corresponding value from another table without make any change to the database
I am trying to add a column to my website without making any changes to my database -
In a FilterView, how can I keep track of "selected" items when paginating
I'm learning Django. I'd like to display a list of products, select some and send them to be processed by a method (that will generate pdf price tags for each of them). I want to be able to browse the list and filter it. The selected products, should be "extracted" of the main list and appear in another list. So far I'm able to filter and paginate. For the selecting par thought I'm kind of stuck. I use checkbox to select the products. The problem is that every time I modify a filter, all the checkboxes are reset. I'm using a FilterView. In my template, the filters buttons are just links with "href=" containing the values for the filters as url parameters. The view take parameters via request.GET.get in the get_context_data method I suppose I could add a filter button that would add the product pk as a url parameter, but it doesn't sound very clean to me. What would be the most djangoic way to achieve this? -
Use Non default database with ManyRelatedManager methods in django
I want to use a non default database with ManyRelatedManager's set method in django. I have tried the following methods: By mentioning the using method in the query It gives me the following error: AttributeError: 'QuerySet' object has no attribute 'set' By using the db_manager with the relatedmanager like this: modelA.modelB_set.db_manager('new_db').set(modelB_list) This doesn't give any error, but it uses the default database to do this. Is there any way that I can use a non default database with set method of ManyRelatedManager? Thanks in advance. -
How to get result from a three-referenced foreign key?
I have models that look like this class Tweets(models.Model): description = models.TextField(blank=True, null=False, default="", max_length=255) createdAt = models.DateTimeField(auto_now_add=True, null=True, blank=True) updatedAt = models.DateTimeField(auto_now=True) owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL ) class TweetsLike(models.Model): tweetId = models.ForeignKey( Tweets, on_delete=models.SET_NULL, null=True, blank=True ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL ) createdAt = models.DateTimeField(auto_now_add=True, null=True, blank=True) updatedAt = models.DateTimeField(auto_now=True) A tweet can be liked by one UserModel once only, and I would like to display an un-like button if person liked, how can I do this on ListView? Current CBV ListView with Form Mixin: class ListWithForm(ListView, ModelFormMixin): model = Tweets ordering = ["-createdAt"] paginate_by = 5 form_class = TweetForm def get(self, request, *args, **kwargs): self.object = None self.form = self.get_form(self.form_class) # Explicitly states what get to call: # return HttpResponseRedirect("/") return ListView.get(self, request, *args, **kwargs) def post(self, request, *args, **kwargs): # When the form is submitted, it will enter here self.object = None form = TweetForm(request.POST) if form.is_valid(): newTweet = form.save(commit=False) newTweet.owner = request.user newTweet.save() # Here ou may consider creating a new instance of form_class(), # so that the form will come clean. # Whether the form validates or not, the view will be rendered by get() return self.get(request, *args, **kwargs) … -
how can i read and convert xlsx data in django with class base view?
from django.shortcuts import render import pandas import xlrd import json from django.http import HttpResponse Create your views here. from django.views.generic.list import ListView from .models import DataModel class Datalist(ListView): # specify the model for list view model = DataModel template_name="datamodel_list.html" def data(self,request): wb_data=xlrd.open_workbook('exelcsv_csv.xlsx',encoding_override='CORRECT_ENCODING') exel_data=pandas.read_excel(wb_data) json_data=exel_data.to_json() aDict = json.loads(json_data) total=json.dumps(aDict,ensure_ascii=False) return HttpResponse(total) -
Integrate Keycloak 13.x with Django 4.x and OIDC
I need to integrate Keycloak 13.0.0 authentication/authorization to a Django 4.0.6 project using OIDC. There are a couple of libraries that claim to integrate Keycloak and Django (for example django-keycloak, boss-oidc) but they haven't been updated in years, or are explicitly not compatible with newer versions of Django. Are there any updated (and preferably well-documented) libraries to do this integration? -
Django ignore user_permissions
In my django project I use only group permissions. The debug-toolbar shows me that a request is made against user_user_permissions as well as against auth_group_permissions. Even if the model user_user_permissions is not populated, is it possible to avoid this query? Regards -
Database graphic display using Django or Sqlite
Is there any software or package that can help me get a graphical representation of my database. I want something that can take as input my Django models or my sqlite database and provide me with a graphical representation of tables and relationships. -
How do i really move forward with Django, exploring and covering more advanced topics like docker implemetation and postgresql?
I feel like I am stuck in the middle of moving from basic Django to Django for professionals. i can't just move on. I need your advice. How do i begin to work with Docker implementation and PostgreSQL? -
cant access the admin panel of my django project [closed]
: return debug, technical_500_response(request, *exc_info) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/views/debug.py", line 66, in technical 500 html reporter.get_traceback_html() = File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/views/debug.py", line 386, in get traceback html return trender(c) File "/data/user/0/ru.ilec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 175, in render return self._render(context) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 167, in _render return self, nodelist, render(context) File "/data/user/0/ru. iiec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 1000, in render return SafeString("join([node render_annotated(context) for node i self) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 1000, in return SafeString( .join([node render annotated(context) for node i self))) File "/data/user/0/ru, ilec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 958, in render anno tated return self.render(context) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 1059, in render output = self, filter_expression, resolve(context) File "/data/user/0/ru. iiec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/template/base.py", line 735, in resolve obj = template_localtime(obj, context, use_tz) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 184, in template I ocaltime return localtime(value) if should convert else value File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 203, in localtime timezone get_current_timezone() = File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 84, in get_current timezone return getattractive, "value", get_default_timezone()) File "/data/user/0/ru.lec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/site-packages/django/utils/timezone.py", line 70, in get_default timezone return zoneinfo. ZoneInfo(settings. TIME ZONE) File "/data/user/0/ru.iec.pydroid3/files/aarch64-linux-android/lib/py thon3.9/zoneinfo/common.py", line 24, in load tzdata raise ZoneInfoNotFoundError("No time zone found with key (key}") zoneinfo, common, ZoneInfoNotFoundError: 'No time zone found with key UTC ་ [26/Jul/2022 13:41:38] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 59 -
Django user authentication with Azure AD and app roles
Outline I want to integrate Azure Active Directory for authentication and authorization. Question How do I integrate the msal library into a Django web app, because the official Azure examples are using Flask? And how to map the AppRoles I have defined in the Azure AD app registration to Django groups defined in the Django backend? -
celery_beat relations not found by postgres using docker
I have a Django app with Nginx, Gunicorn, PostgreSQL and Celery that I've been dockerizing. When trying to add celery_beat in my docker-compose.yml, I get a django.db.utils.ProgrammingError: relation "django_celery_beat_periodictask" does not exist even though the migrations have been ran successfully. Locally, starting celery_beat works fine, but here it returns this error and I have no idea where it could be coming from. Postgres doesn't seem to find the relation django_celery_beat_periodictask but it should since the migrations were done. Is there something I misunderstood ? Here is my docker-compose.yml: version: '3.8' services: rabbitmq3: container_name: rabbitmq image: rabbitmq:3-alpine ports: - 5672:5672 postgres: container_name: postgres hostname: postgres image: postgres:latest env_file: - env environment: - POSTGRES_USER=user - POSTGRES_PASSWORD=password - POSTGRES_DB=db ports: - "5432:5432" restart: on-failure volumes: - postgresql-data:/var/lib/postgresql/data django_gunicorn: container_name: django_gunicorn volumes: - static:/app/static - media:/app/media env_file: - env build: context: . ports: - "8000:8000" command: sh -c "python manage.py migrate && python manage.py collectstatic --no-input && gunicorn main.wsgi:application --bind 0.0.0.0:8000" depends_on: - postgres nginx: container_name: nginx build: ./nginx volumes: - .:/code - static:/static ports: - "80:80" depends_on: - django_gunicorn celery: container_name: celery volumes: - media:/app/media build: context: . command: celery -A main worker -P eventlet -c 100 -l INFO env_file: - env restart: … -
what's the equivalent of django orm's values_list in sqlalchemy?
I want to extract all the ids of the first query old_devices_or_user_tokens = DeviceDAO(session=session).filter__or(user_id=user.id,device_id=token_obj.device_id) DeviceDAO(session=session).delete(synchronize_session=False, ) so that i can pass the list of ids in the delete statement with something like DeviceDAO(session=session).delete(synchronize_session=False, id__in=old_devices_or_user_tokens) In django ORM i could have just done old_devices_or_user_tokens.values_list('id', flat=True) -
How do I loop a intergerFIeld in django templates?
I have to loop an element according to the dynamic data. I have an INTeger Field. Here's what I want to loop: <li class="list-inline-item"><i class="fas fa-star text-warning"></i></li> about 5 times max and 1 min. Thanks -
Django not finding database object when trying to render view
I'm getting the following error when I go to the /val/4/13/bs url: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/val/4/13/bs Raised by: valapp.views.BSDetail No balance sheet found matching the query Here is the views.py code: class BSDetail(generic.View): def get(self, request, *args, **kwargs): view = BSDisplay.as_view() return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = PostEvent.as_view() return view(request, *args, **kwargs) class BSDisplay(generic.DetailView): template_name = 'valapp/balsheet.jinja' model = BalanceSheet def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) entityobject = get_object_or_404(Entity, pk=self.kwargs['pkent']) context['bsinfo'] = BalanceSheet.objects.filter(company = entityobject) return context class EntityDetail(generic.View): def get(self, request, *args, **kwargs): view = EntityDetailDisplay.as_view() return view(request, *args, **kwargs) class EntityDetailDisplay(generic.DetailView): model = Entity template_name = 'valapp/entitydetail.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) engobject = get_object_or_404(Engagement, pk=self.kwargs['pk']) entobject = get_object_or_404(Entity, pk=self.kwargs['pkent']) context['engagement'] = engobject context['entity'] = entobject return context The urls.py code is: app_name = 'valapp' urlpatterns = [ path('', views.IndexView.as_view(), name='index'), path('<int:pk>/', views.ValDetailView.as_view(), name='engagement'), path('<int:pk>/<int:pkent>/', views.EntityDetail.as_view(), name='entitydetail'), path('<int:pk>/<int:pkent>/bs', views.BSDetail.as_view(), name='bs'), path('newval/', views.newval, name="newval"), path('<int:pk>/newentity/', views.NewEntity.as_view(), name="newentity"), ] Here is the models.py: class BalanceSheet(models.Model): company = models.ForeignKey(Entity, on_delete=models.CASCADE) account_type = models.CharField(max_length=50, choices = BS_ACT_CHOICES) value = models.DecimalField(max_digits=20, decimal_places=2) name = models.CharField(max_length=100) year = models.IntegerField(choices=YEAR_CHOICES, default=2022) tab_abv = models.DecimalField(max_digits=20, decimal_places=2, default=0) tab_rdt = models.DecimalField(max_digits=20, decimal_places=2, default=0) tab_debt = … -
How to upload images to wagtail images using django rest framework?
I have a bit of a problem, any help would be appreciated: I have a model which has an icon field, which is related to wagtailimages.Image How do I upload images to that field which is ForeignKey related to wagtailimages.Image This is the serializer of my model: class CommunitySerializer(serializers.ModelSerializer): class Meta: model = Community fields = [ "id", "icon", "name", "description", "short_description", "website", ] And this is my models.py: class Community(ClusterableModel): ............ icon = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+", ) .......... So, how should i go about uploading images to the "icon" field using DRF? I have tried to use both the DRF's FileField and ImageField but without success, maybe I am missing something? -
How can I get a size of SVG in Python?
From Django CMS admin I upload a SVG image and I need to validate its size For some other formats (jpeg, png) it works just fine def validate_social_icon(fieldfile_obj): w, h = get_image_dimensions(fieldfile_obj) if w > 100: raise ValidationError("The icon width must be <= 100 pixels. Yours is %i pixels." % w) if h > 100: raise ValidationError("The icon height must be <= 100 pixels. Yours is %i pixels." % h) But if I upload a SVG file, it says h and w are None, so there is an exception bc Python can't compare None to int. Is there a similar way to do that for SVG? -
Placing functions in vue.js that accept parameters and do not operate on variables in the component
I've been trying to wrap my head around best practices in vue.js (+ pinia as store). I'm coming from using Django templates where one can use template functions on variables to massage data for displaying. However, I'm not sure where to put such functions in vue.js. Suppose I have a variable holding a string and I want to cut off trailing digits. The variable is coming from a vue.js for-loop over a dict variable present in the store. I would create some function to do so: displayString(s) { const re = /\d+$/; return s.replace(re, ""); } I would use it in the template in some way: <th v-for="(item, index) in store.myDict" :key="index"> {{ displayString(item) }} </th> To me, neither place for putting the function (methods/computed or actions/getters in pinia) would be right as they are all intended to use data from the store or component (and not all of them accept parameters anyway). Conceptually, where would a function go that does not return data from the component or store but accepts a parameter and returns a modified version of it? Or should I design things differently, writing getters/computed functions that massage the dict in some way for displaying the data? …