Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to debug "INSUFFICIENT_ACCESS" from django-auth-ldap
I have a LDAP server form Authentik and configured my NetBox wich uses django-auth-ldap to authenticate via said LDAP server. I can't login with any user. Turning on django logging I get this for all login attempts: Caught LDAPError while authenticating MYUSER: INSUFFICIENT_ACCESS({'msgtype': 111, 'msgid': 3, 'result': 50, 'desc': 'Insufficient access', 'ctrls': [], 'info': 'Insufficient Access Rights'}) On the ldap-server the logs show: {"bindDN":"cn=MYUSER,ou=users,dc=authentik,dc=vulca,dc=run","client":"10.42.3.1","event":"User has access","level":"info","requestId":"250807a2-b342-41bb-ace4-5b3a66cbcd32","timestamp":"2022-04-27T19:06:14Z"} {"bindDN":"cn=MYUSER,ou=users,dc=authentik,dc=vulca,dc=run","client":"10.42.3.1","event":"Allowed access to search","group":"authentik Admins","level":"info","requestId":"250807a2-b342-41bb-ace4-5b3a66cbcd32","timestamp":"2022-04-27T19:06:14Z"} {"bindDN":"cn=MYUSER,ou=users,dc=authentik,dc=vulca,dc=run","client":"10.42.3.1","event":"Bind request","level":"info","requestId":"250807a2-b342-41bb-ace4-5b3a66cbcd32","timestamp":"2022-04-27T19:06:14Z","took-ms":1792} {"bindDN":"cn=akadmin,ou=users,dc=authentik,dc=vulca,dc=run","client":"10.42.3.1","event":"User has access","level":"info","requestId":"c87e095a-66c8-4ed9-8f59-1f3ea6df7cc2","timestamp":"2022-04-27T19:06:16Z"} {"bindDN":"cn=akadmin,ou=users,dc=authentik,dc=vulca,dc=run","client":"10.42.3.1","event":"Allowed access to search","group":"authentik Admins","level":"info","requestId":"c87e095a-66c8-4ed9-8f59-1f3ea6df7cc2","timestamp":"2022-04-27T19:06:16Z"} {"bindDN":"cn=akadmin,ou=users,dc=authentik,dc=vulca,dc=run","client":"10.42.3.1","event":"Bind request","level":"info","requestId":"c87e095a-66c8-4ed9-8f59-1f3ea6df7cc2","timestamp":"2022-04-27T19:06:16Z","took-ms":1734} akadmin is the superuser in Authentik used to bind in NetBox auth. MYUSER is the user trying to login in NetBox. The question is how I know who is accessing what that is being denied so I can fix it. As I said akadmin is a superuser in Authentik, so I can't make sense of the error message. Also tried giving MYUSER superuser privileges in Authentik, but had no effect. -
Inner Join Two Django Querysets from Related Models
TL;DR: Is there a way to inner join two related querysets if they are based on different models? Suppose I'm trying to manage access controls for a filesystem, and I have models for User, Folder, and File. A User can access a File if it is public, OR if they can access the File's Folder. I already have a Django queryset that includes all Folders for a User: # I already have this queryset... user_folders = Folder.objects.filter( Q(is_public=True) | Q(owner=user) | Q(folder_shares__user=user), deleted_at__isnull=True, ) Now the problem: I also want a queryset that includes all Files for a User. And I want to recycle the users_folders queryset so I don't have to rewrite all the same conditions again. # ...so I don't want to rewrite the same conditions for this queryset user_files = File.objects.filter( Q(is_public=True) | Q(folder__is_public=True) | Q(folder__owner=user) | Q(folder__folder_shares__user=user), deleted_at__isnull=True, folder__deleted_at__isnull=True, ) This is a simplified example. In my real codebase, the two querysets are much more complicated, and it's a 3-level hierarchy. So currently, if the sharing rules change, I have to remember to update 3 different complex queries across the app. That's easy to screw up, and the costs of getting it wrong are really high. … -
Wagtail/Django: How to pass a Page model object as a default value for a streamfield block?
How can I pass the user selected value for background_color object that is in my PostPage Page class as the default value for another ColorField that's within my streamfield blocks? class PostPage(Page): # The user selected value for background_color is the object that I'm trying to pass as a default for a streamfield block. background_color = ColorField(default="#000000") # streamfield in question blog_builder = StreamField(BlogFeatures(), blank=True) content_panels = Page.content_panels + [ NativeColorPanel('background_color'), StreamFieldPanel("blog_builder"), ] edit_handler = TabbedInterface([ ObjectList(content_panels, heading="Content"), ]) Here is my streamfield class that uses StreamBlock: class BlogFeatures(StreamBlock): simple_list = SimpleList() I use a Structblock to help achieve my streamfield goals: class SimpleList(StructBlock): ... # how can I set the default value of this background_color to match the user selected value from the Page Model called PostPage. background_color = NativeColorBlock(default="#ffffff") ... -
How to display a gallery of images of a product after clicking on the first image?
So in short, I have a ListView in Django which displays pictures with tables on the website. Then I have a DetailView where I am placing a second webpage to use with slugs but I guess my logic is wrong. I want to be able to click on a particular picture/ table and this would redirect me to another page( possible created with slug) where I can display more pictures of the same table. I have created everything so far but I am thinking my logic is wrong. You don't have to write code, just please explain what is the correct way of doing it since I am doing it for the first time. First I created a Categories model which lists categories such as: tables, kitchens, wardrobes, bedrooms. I then created Image category where I would have title and image and so on but this was okay for one of the views but for this one I want to display multiple pictures as I mentioned and I saw some code which enabled me to have multiple images. views.py class TableCategoryListView(ListView): model = Images template_name = 'main/projects/tables.html' context_object_name = 'category_images' queryset = Images.objects.filter(category__category_title="tables") class TablesDetailView(DetailView): model = Images template_name = … -
set the logged in user to created_by for django CreateView
Apart from form_valid() method what are the other efficient ways i can set the user to created by. views.py class CreatEEView(LoginRequiredMixin, CreateView,): form_class = '' template_name = '' success_url = '' def form_valid(self, form): instance = form.instance instance.created_by = Model.objects.get(user=self.request.user) instance.save() return super().form_valid(form) -
Django Email Verification
I'm adding a feature to the social media website project that is email verification while signing up for new users. But I'm unable to create profile object to generate token using uuid4 class in administration page of django and also the data between the user object and profile object are not getting linked to each other I have attached the link to the project https://github.com/nitinjain-tech/django_email_verification please help me out -
Search functionality in CBV list view
As described in this post. My project has two types of users, clients and sellers. I have created a list view (A class based list view) for the seller, where he/she can see all of his/her clients. However, I want to implement search functionality in the list view, to make it easier for the seller to find the right client. I tried to implement the same solution that was given in this post this post, but I was not able to make it work. So my question is, how should I define the "get_queryset" to get the desired outcome? -
I am making a website using django and tailwind css. But in Cpanel I am getting this command error of Node Js path. Any suggestions what I can do?
CommandError: It looks like node.js and/or npm is not installed or cannot be found. Visit https://nodejs.org to download and install node.js for your system. If you have npm installed and still getting this error message, set NPM_BIN_PATH variable in settings.py to match path of NPM executable in your system. Example: NPM_BIN_PATH = "/usr/local/bin/npm" -
wifi_add() missing 1 required positional argument: 'request' when try to create an object
I have created this post because I couldn't find it on SO. I am not using class so that is why it is weird to get a 'request not found error'. I am facing this problem for 2 days here is my code thank you. The same problem was at my user ajax view but I solve it by changing User.objects.create() to form.save in view. But not possible to solve in here please take a look to the code I really thank you. #models.py class Wifi(models.Model): ssid = models.CharField(max_length=150) password = models.CharField(max_length=150) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.ssid + " " + self.user.username #views.py def configrations(request): wifi_form = WifiForm() if request.method == 'POST' and request.POST.get("operation") == "wifi": wifi_form = WifiForm(request.POST) if wifi_form.is_valid(): data = wifi_form.cleaned_data wifi_obj = Wifi.objects.create(**data, user=request.user) ctx = { 'created': True, 'success': True, 'ssid': wifi_form.cleaned_data['ssid'], 'password': wifi_form.cleaned_data['password'], 'msg':'Wifi configuration created', } return JsonResponse(ctx) return render(request, 'web/configrations.html',{'wifi_form':wifi_form}) #my forms.py class WifiForm(forms.ModelForm): ssid = forms.CharField(widget=forms.TextInput( attrs={'class': "form-control"})) password = forms.CharField(widget=forms.PasswordInput( attrs={'class': "form-control"})) class Meta: model = Wifi fields = ['ssid','password'] my ajax func: <script> $('#submit_wifi').click(function(){ var wifi_name = $('#wifi_name').val() var wifi_pass = $('#wifi_pass').val() $.ajax({ type: "POST", url: "{% url 'config' %}", headers: { 'X-CSRFToken': '{{ csrf_token }}' … -
Using annotate and distinct(field) together in Django
I've got a bunch of reviews in my app. Users are able to "like" reviews. I'm trying to get the most liked reviews. However, there are some popular users on the app, and all their reviews have the most likes. I want to only select one review (ideally the most liked one) per user. Here are my objects, class Review(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='review_user', db_index=True) review_text = models.TextField(max_length=5000) rating = models.SmallIntegerField( validators=[ MaxValueValidator(10), MinValueValidator(1), ], ) date_added = models.DateTimeField(db_index=True) review_id = models.AutoField(primary_key=True, db_index=True) class LikeReview(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='likereview_user', db_index=True) review = models.ForeignKey(Review, on_delete=models.CASCADE, related_name='likereview_review', db_index=True) date_added = models.DateTimeField() class Meta: unique_together = [['user', 'review']] And here's what I currently have to get the most liked reviews: reviews = Review.objects.filter().annotate( num_likes=Count('likereview_review') ).order_by('-num_likes').distinct() As you can see, the reviews I get will be sorted by the most likes, but its possible that the top liked reviews are all by the same user. I want to add distinct('user') here but I get annotate() + distinct(fields) is not implemented. How can I accomplish this? -
Redis server on glitch
I am new user on glitch and i am not aware how to start Redis server for Django project on glitch. Please help me to do so or suggest me any other platform which is free. -
Django model form create and update
I have a model form called Record Category which has only field called name on my 2 pages 1.record_category/create/ 2.record_category/update/ how can i write my formview for both updating and creating? models.py class RecordsCategory(models.Model): name = models.CharField(max_length=255, blank=True) views.py class RecordCategoryView(FormView): ? -
Django formsets of dynamic forms
I have several arbitrary datastructures that I want to be filled by a user and I think the django formsets are the most suitable way to deal with it, thanks to prefixes, but I'm not sure. Let's say I always have an initial data whose keys and values can vary depending on the situation, but for this example I will use: fields = { "first" : forms.IntegerField(), "second" : forms.CharField() } I have the following class to create forms dynamically: class fieldsForm (forms.Form): pass Thus, I create a class dynamically: DynamicForm = type('DynamicForm', (fieldsForm,), fields) Then, I create a formset and I instantiate it: dynamicFormSet = forms.formset_factory(DynamicMsgForm) formset = dynamicFormSet() The key is I can have extra field dicts that I want to handle on the same formset giving to each dict form instance an index, for example: another = { "first" : forms.IntegerField(), "second" : forms.CharField(), "third" : forms.IntegerField() } Finally, I create the class dynamically again, I instantiate it and I try to include it to the previous formset instance: DynamicForm = type('DynamicForm', (fieldsForm,), another) anotherFormInstance = DynamicForm() formset.add_fields(form=anotherFormInstance, index=1) My problem is that the formset is not being updated with the "another" form instance, I think I've … -
Can't assign a valid instance to a FK relation when creating a related instance
I have the following related models class Period(models.Model): """ A table to store all periods, one period equals a specific month """ period = models.DateField() def __str__(self): return f'{self.period}' class Payment(models.Model): """ A table to store all payments derived from an offer """ # Each monthly payment relates to an offer offer = models.ForeignKey(Offer, on_delete=models.CASCADE) month = models.ForeignKey(Period, on_delete=models.CASCADE) amount = models.PositiveIntegerField() ... for key, value in payments.items(): # Get the period of the payment or create it period = Period.objects.get_or_create(period=key) print(period) Payment.objects.create( offer=offer_instance, month=period, amount=value ) which raises ValueError: Cannot assign "(<Period: 2022-05-01>, False)": "Payment.month" must be a "Period" instance. although print(period) returns (<Period: 2022-05-01>, False) which to me looks like a valid instance? -
why model object attribute not change when i try to access it directly without assign to variable
i try here to change title but this not work. but when assign object to variable change is work. i need any one explain why it work when i assign object to variable and why not work when access it directly -
cannot import name 'python_2_unicode_compatible' from 'django.utils.encoding
I was trying to run server but the terminal always showed me that "ImportError: Could not import 'rest_framework.negotiation.DefaultContentNegotiation' for API setting 'DEFAULT_CONTENT_NEGOTIATION_CLASS'. ImportError: cannot import n ame 'python_2_unicode_compatible' from 'django.utils.encoding' (C:\Users\86133\PycharmProjects\pythonProject4\venv\lib\site-packages\django\utils\encoding.py)." -
where are django-html variables defined by models?
in django, where do you get variables from the models to put in a .html this is the models of my app: class Member(models.Model): active = models.BooleanField( verbose_name=_("active"), default=True, ) image = models.ImageField( verbose_name=_("Team Menber image"), blank=True, null=True, ) name = models.CharField( verbose_name=_("Team Menber name"), max_length=100, default="", ) role = models.CharField( _("Team Menber role"), max_length=50, default="", ) order = models.PositiveIntegerField( verbose_name=_("order"), default=0, ) biography = models.TextField( verbose_name=_("Team menber bio"), ) class Meta: ordering = ["order", "name"] def __str__(self): return self.name where in my html would i get my_object.name for example? and how can i get the list of all instances of this class? my views: class TeamView(ListView): """ list view of the menbers(image, name, role) """ model = Member class MenberView(DetailView): """ Detail view of the menbers(image, title, role, bio) """ model = Member I know in django i would need to {{my_object.my_var}} inside the template but what is my_object and my_object.my_var defined so i can call them? -
Need to do POST method for the Nested serializers using django
models.py class Organisation(models.Model): """ Organisation model """ org_id = models.AutoField(unique=True, primary_key=True) org_name = models.CharField(max_length=100) org_code = models.CharField(max_length=20) org_mail_id = models.EmailField(max_length=100) org_phone_number = models.CharField(max_length=20) org_address = models.JSONField(max_length=500, null=True) product = models.ManyToManyField(Product, related_name='products') org_logo = models.ImageField(upload_to=upload_org_logo, null=True, blank=True,) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) serializers.py class Organisation_Serializers(serializers.ModelSerializer): product = Product_Serializers(read_only=True, many=True) class Meta: model = Organisation fields = ('org_id', 'org_name','org_address', 'org_phone_number', 'org_mail_id','org_logo','org_code','product',) #depth = 1 def create(self, validated_data): org_datas = validated_data.pop('product') org = Organisation.objects.create(**validated_data) for org_data in org_datas: Product.objects.create(artist=org, **org_data) return org views.py class Organisation_Viewset(DestroyWithPayloadMixin,viewsets.ModelViewSet): renderer_classes = (CustomRenderer, ) #ModelViewSet Provides the list, create, retrieve, update, destroy actions. queryset=models.Organisation.objects.all() parser_classes = [parsers.MultiPartParser, parsers.FormParser] http_method_names = ['get', 'post', 'patch', 'delete'] serializer_class=serializers.Organisation_Serializers I able to get the product data as a array of dict while performing GET method. But while i tried to post it Iam getting an error as "Key Error product ". I need to get the data as Iam getting now and it would be fine if I POST based on the array of product_id or the array of data which I receive in the GET method.I was stuck on this part for 3 days and still I couldn't able to resolve it. Please help me resolve this issue your helps … -
how to implement email_user to signals in Django?
I am trying to write a signal that will send an email to the user if the status will change but I am getting this error: AttributeError at /admin/article/requests/ 'str' object has no attribute 'email_user' models.py class Requests(models.Model): STATUS = ( ('received', _('Question received')), ('in_progress', _('In progress')), ('published', _('Published')), ) email = models.EmailField() user = models.CharField(max_length=255, blank=True, null=True,) title = models.CharField(max_length=1000, blank=True, null=True, default='') body = models.TextField('Description') publish_date = models.DateTimeField('default=timezone.now) owner = models.ForeignKey(User, blank=True, null=True, on_delete=models.SET_NULL) status = models.CharField(max_length=32, choices=STATUS, default='received') def __str__(self): return str(self.title) def send_email_to_user(sender, instance, **kwargs): subject = 'Status of your request has changed' message = render_to_string('user/request_status.html', { 'user': instance.email 'status': instance.status }) user.email_user(subject, message) post_save.connect(send_email_to_user, sender=QuestionRequests) Any tips on how to solve this issue would be appreciated. -
how to show all info and all connected tables with certain object after selecting it in <select>?
as you can see on a picture i have select menu where all my so called "video libraries" are shown. The first question is - is there any way to show all data about certain selected "video library" (every video library has its won adress)? And the second question - every video library is connected with couple of different tables (Staff, Films, Ranks etc.) by ForeignKey - how to show data which is connected with certain video library? class VideoLibrary(models.Model): shop_id = models.AutoField(primary_key=True, unique=True) shop_name = models.CharField(max_length=264) adress = models.TextField(max_length=264, default='') class Staff(models.Model): staff_id = models.AutoField(primary_key=True, unique=True) nsf = models.CharField(max_length=264) living_adress = models.TextField(max_length=264) shop_id = models.ForeignKey(VideoLibrary, on_delete=models.CASCADE) -
How to customize graphene-django response?
I have a GraphQL API with graphene-django and I want to customize the query response. Here is the default response; { "data": { "materials": { } }, "errors": { } } However, I want to customize it like this; { "data": { "materials": { } }, "errors": { }, "extra_field": { } } How can I do this? -
NoReverseMatch: Redirect to a new page in Django with a query from a template
I want to redirect from inside my HTML Template to a new page and also pass a query to that page as a GET request query. The HTML code looks like this. <th scope="row">{{ forloop.counter }}</th> <td>{{ project.article_title }}</td> <td>{{ project.target_language }}</td> <td> <a href="{% url 'translation/{{project.id}}/' %}" class="btn btn-success">View Project</a></td> This doesn't redirect and I get the following error. NoReverseMatch at /manager/ Reverse for 'translation/{{project.id}}/' not found. 'translation/{{project.id}}/' is not a valid view function or pattern name. My URL pattern looks like this urlpatterns = [ path('', views.project_input_view, name='main'), path('login/', views.login_user, name='login'), # path('register/', views.register_user, name='register'), path('translation/<str:pk>/', views.translation_view, name='translation'), path('manager/', views.manager_view, name='manager_dashboard'), path('annotator/', views.annot_dashboard_view, name='annot_dashboard'), ] However, if I write the following then it works. <th scope="row">{{ forloop.counter }}</th> <td>{{ project.article_title }}</td> <td>{{ project.target_language }}</td> <td> <a href="{% url 'main' %}" class="btn btn-success">View Project</a></td> but I want to redirect to the translation page along with the query. How can I achieve that? -
Handle large amounts of time series data in Django while preserving Djangos ORM
We are using Django with its ORM in connection with an underlying PostgreSQL database and want to extend the data model and technology stack to store massive amounts of time series data (~5 million entries per day onwards). The closest questions I found were this and this which propose to combine Django with databases such as TimescaleDB or InfluxDB. But his creates parallel structures to Django's builtin ORM and thus does not seem to be straightforward. How can we handle large amounts of time series data while preserving or staying really close to Django's ORM? Any hints on proven technology stacks and implementation patterns are welcome! -
How to group a queryset by a specific field in Django?
I have a qs qs_payments that returns the following: [ { "id": 19, "month": "2021-05-01", "amount": 3745, "offer": 38 }, { "id": 67, "month": "2021-03-01", "amount": 4235, "offer": 39 }, { "id": 68, "month": "2021-04-01", "amount": 4270, "offer": 39 }, { "id": 69, "month": "2021-05-01", "amount": 4305, "offer": 39 } ] I now try to re-group the data so that each month contains all items of that particular month (in the given example there would be two nested items for May/2021-05-21) I tried the following using itertools but this returns Payment object is not subscriptable. Context is that I want to render one component with its line items in React.js. class PayrollRun(APIView): def get(self, request): # Loop payment table for company related payments, create dict of dict for each month # Get todays date today = datetime.date(datetime.now()) # Get the related company according to the logged in user company = Company.objects.get(userprofile__user=request.user) # Get a queryset of payments that relate to the company and are not older than XX days qs_payments = Payment.objects.filter(offer__company=company).filter( month__gte=today - timedelta(days=600), month__lte=today ) payment_runs = [{'subject': k, 'Results': list(g)} for k, g in itertools.groupby(qs_payments, key=itemgetter('month'))] print(payment_runs) serializer = PaymentSerializer(qs_payments, many=True) return Response(serializer.data) The desired outcome is … -
Live camera feed is not working on ip address of wifi router on django server
I have a django server setup and I want to access the website from an android device for testing. The webpage consist of live camera feed. Here's the html code for the camera feed. <canvas id="camera--sensor"></canvas> <video id="camera--view" autoplay playsinline></video> <img src="//:0" alt="" id="camera--output"> <button id="camera--trigger">Take a picture</button> Now when i run python manage.py runserver, the camera feed is visible in the localhost. But on running python manage.py runserver wifi_ip:port_no, the camera feed is not working. Is there anything i can do to make it work? Any advice is appreciated.