Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Dynamically updating Django form fields
so I've been learning Django for a work project, and have been running into a few bumps with forms and how to update / eventually save them. So the goal here is for someone to be able to log in, select a date, and have that date populate a drop-down with a list of all the jobs that person had that day. When they then select a job from that dropdown, it fills in certain parts of the rest of the form with that job data from our database. My primary question currently is, before I added the date picker, I set the choices for the job dropdown in forms.py, and they were strictly for todays date. Now with the ability to set a date, how do I feed those choices back in dynamically when a different date is selected? These are fairly messy right now, but this is what I've got: forms.py df, jobs = get_todays_jobs() choices = tuple((m, m + ' - ' + df[df['Inv_Num'] == m]['Customer'].iloc[0].title()) for m in df['Inv_Num']) class JobForm(forms.Form): '''Our default job completion form.''' date = forms.DateField(label='Install Date', widget=forms.widgets.DateInput(attrs={'class': 'datepicker', 'onchange': 'this.form.submit();' })) order = forms.CharField(widget=forms.Select( choices=choices, attrs={'onchange': 'this.form.submit();'}), label='Order #') crew = forms.CharField(widget=forms.Textarea, … -
Multiple users authentication with one account in Python Django?
I want to make an app where ie 5 users can use one account, these users should have different permissions within this account, and one of them should have Admin permissions (create users connected to account, delete users). Which way should I move to? -
Pass multiple queryset to serializer and calculate in DRF
I want to pass multiple queryset which are filtered by different keyword. qs_x = timeseries.objects.filter(html__pk=pk).filter(keyword=key_x) qs_y = timeseries.objects.filter(html__pk=pk).filter(keyword=key_y) I want to pass this multiple queryset and calculate based on these two queryset. I tried below but this run serializer two times receiving each queryset separately. serializer = scatterChartSerializer(combine_qs,many=True) I want to calculate receiving these two queryset together. Does anyone know how to achieve this? -
Change MagicMock return_value instance method callable to PropertyMock
I'm trying to change the callable for an instance method on my MagicMock to a PropertyMock as that is how it is accessed (Django model column). But test fails with _mock_self = <PropertyMock name='get().my_prop' id='4524632776'> Given the following code # view def get(self request): # stuff... obj = MyModel.objects.get(id=2) # more stuff... print(obj.my_prop) some_val = obj.my_prop # tests def test_my_test(mocker): obj_get = mocker.patch("app.views.MyModel.objects.get") obj_prop = mocker.PropertyMock(return_value=1) # This should translate to an instance of MyModel i.e. MyModel().my_prop obj_get.return_value.my_prop = obj_prop # run view obj_prop.assert_called_once() # Says never invoked The print statement shows <PropertyMock name='get().my_prop' id='4524632776'> So it appears it is the same instance it just is not actually being invoked -
Django view undoing what my code has achieved
My model: My 'event' references several 'items' through the following declaration: items = models.ManyToManyField('Item') My Form: There are lots of items that I list in a bootstrap multi-select widget. To save time, I added a checkbox to the form that will add the descendants of the selected 'items' to my 'event' as well. addToChildren = forms.BooleanField(required=False, label="Add event to descendants of selected item") My View: Once the form is submitted, I add the descendants with the following code: def form_valid(self, form): event = form.save() if form.cleaned_data['addToChildren'] == True: #add to children if told to do so. print("items before save") print(self.object.items.all()) for x in range(0,form.cleaned_data['items'].count()): itm = form.cleaned_data['items'][x] for descendant in itm.get_descendants(): self.object.items.add(descendant)#deletes when updated print("items after save") print(self.object.items.all()) return super(EventUpdate, self).form_valid(form) My Problem: The print statements clearly show that the descendants of the selected items in are getting added to self.object (my event object). The issue is that the return statement disregards my changes, adds selected items to my event, and removes all unselected items from my event. I would like that to stop. Is there a way to append information to form.cleaned_data from a django view? -
How to pass a variable in Django template?
I have a candidate search view. I want to search for candidates with this view, and then if the view was called from clicking on an edit candidate If the view was called from clicking on read candidate details I somehow need to call the one view, but to pass it a parameter. normally i pass parameters using (?P\d+/$) but i am not sure how to pass a parameter that says 'update' or 'read'. I don't know if i should use get_context_data, or if i should use some **kwargs (ps if i use **kwargs) i don't know how to pull this off. or if i should use a regex field in the url which is set in the Any advice would be greatly appreciated, as you can see i am confused as to when to use: **kwargs (?P get_context_data in the generic class based view. Thanks. -
Django backend, React frontend and CSRF Post
In my cenario I am using a form in my react frontend (http://localhost:3000/submit) to post to my url http://localhost:8000/api/submit/ However, I have received this response: "detail": "CSRF Failed: CSRF token missing or incorrect." My class view is something like that: from rest_framework.views import APIView from rest_framework.parsers import MultiPartParser, FormParser class Submit(APIView): parser_classes = (MultiPartParser, FormParser) def post(self, request, *args, **kwargs): #custom post I have two questions: How do I decorate dispatch() to exempt csrf? How can I provide CSRF to my frontend? -
Show/hide options in django app to users based on permission
I have a django app and users log in to the app and use it. However I do not want some users to access some parts of my web application. I do not want them to see some parts, if they do not have permission. I tried using permission_required but it shows the tab as it comes from html. Any way to achieve this? -
Django Admin list page: Custom Action Buttons (url) problem, what is wrong?
i have followed this tutorial https://books.agiliq.com/projects/django-admin-cookbook/en/latest/action_buttons.html This is the relevant part of my code: @admin.register(Partner) class PartnerAdmin(admin.ModelAdmin): change_list_template = 'change_list.html' model = Partner . . . def get_urls(self): return super().get_urls() + [path('sync/', self.sync_partners, name='partners_sync_partners')] @staff_member_required def sync_partners(self, request): #TODO: Sync code should go here self.message_user(request, "Partners sync complete") return HttpResponseRedirect("../") The url on template is referenced with {% url 'admin:partners_sync_partners' %} which is pointing to /admin/partners/partner/sync/ And i am getting this error: Partner with ID "sync" doesn't exist. Perhaps it was deleted? The problem may be related with the url generated? my code is inside my app 'partners' in partners/admin.py and my template is under partners/templates/change_list.html -
Replace Group Model in django.auth.group
I am trying to replace/extend the Group Model in Django 2.1. What I found so far was Cusomizing the User Model in Django or this: Customize Django Group Model But it feels wrong to just bind my extended Group fields via a OneToOneField to the preexisting django.contrib.auth.models.Group Model. As this means a second table and one more JOIN on SQL level. I am fairly new to Django/Python, but I believe @Ishwar at Customize Django Group Model could have had a good hint, as I still do not understand it. Did he suggest overriding the Group model of django.contrib.auth.models? How would I do this or is there a better way? Thanks for your help in advance. -
Django 2.0 - order a queryset by a field on the prefetch-related attribute
My goal is to run a query on one model but sort the results based on a field in another model fetched via prefetch_related. Suppose I have two models: class ModelA(models.Model): ...some fields... class ModelB(models.Model): ...some fields... model_a = models.ForeignKey(ModelA, db_column='id') year = models.IntegerField() I have tried: ModelA.objects.filter(...).prefetch_related( Prefetch( 'modelb_set', queryset=ModelB.objects.filter().order_by('-year'), to_attr="modelb_date" ) ).order_by('-modelb_date') but this fails because modelb_date is not a field on ModelA, it's a list. What I want is to order the ModelA queryset according to the latest associated date field (from ModelB). That is, if instance One of ModelA has a modelb_date attribute = [x, y, z] where x.year = 2017 and instance Two of ModelA has a modelb_date attribute = [v, w] where v.year = 2018 then the query would order instance Two before One. I am using Django 2.0, python 3.6, and Oracle 12c. Can anybody help? Thanks! -
How can I fix this bug in my django template?
I have an error in my template. I have tried to see where I've gone wrong, but couldn't identify the bug. This is index.1.html: {% extends 'clinic/clinicbase.html' %} {% load static %} {% block content %} {% if username %} <div class="jumbotron"> <div class="container"> <h3>Welcome, Dr {{ name }}</h3> <p>You can manage your clinics here:</p> <p><a class="btn btn-primary btn-sm" href="#" role="button">Learn more »</a></p> </div> </div> {% if nodoc} {% if clinics %} {% for clinic in clinics %} <div class="col-sm-8 card-deck"> <div class="card mb-3 mr-3 ml-3 shadow bg-white rounded"> <div class="card-body"> <div id="id" style="display: none;">{{ clinic.clinicid }} </div> <h2 class="card-title"> <a href="/appointments/doctor/{{ doc.docid}}"> {{ clinic.name}}</a> </a> </h2> <h6 class="card-subtitle mb-2 text-muted">Label: <a href="/clinic/{{ clinic.label }}/">{{ clinic.label }}</a></h6> <p class="card-text">Phone: <a href="tel:{{ clinic.mobile }}">{{ clinic.mobile }}</a></p> <p class="card-text">About Clinic: {{ clinic.about }}</p> <p class="card-text">Website: <a href="{{ clinic.website }}">{{ clinic.website }}</a></p> <div id="docbtngp" class="d-flex flex-row"> <a href="/appointments/doctor/edit/{{ doc.docid }}" class="btn btn-primary mr-1 mybtndocedit" data-id="{{ doc.docid }}"> <i class="fas fa-user-edit"></i> </a> <a href="/appointments/doctor/appointments/{{ doc.docid }}" class="btn btn-primary mr-1 mybtnviewapp" data-id="{{ doc.docid }}"> <i class="fas fa-calendar"></i> </a> <a href="/appointments/doctor/appointment/add/{{ doc.docid }}" class="btn btn-primary mr-1 mybtnaddapp" data-id="{{ doc.docid }}"> <i class="fas fa-calendar-plus"></i> </a> <a href="/appointments/doctor/remove/{{ doc.docid }}" class="btn btn-danger mr-1 mybtndel" data-id="{{ doc.docid }}"> <i … -
Admin page Django not showing models
I have created superuser and added model to admin.py from django.contrib import admin # Register your models here. from learning_logs.models import Topic admin.site.register(Topic) but I cannot see models in admin panel page. Cannot figure out why! If I, on purpose, type some syntax error inside admin.py I do not receive any kind of error message. -
ORM 'like' query in django python
views.py items=ItemVariation.objects.filter(item__restaurant__id = i['restaurant']['id'],keyword__name__in=keyword,keyword__mood__moods=mood).select_related() i have this query i need to use keyword__name__in=keyword as a like i'm using PostgreSQL database -
DRF IntegrityError: NOT NULL constraint failed: user_id
I can't figure out how to pass user object to the following serializer: class ReviewSerializer(serializers.ModelSerializer): user = UserSerializer(read_only=True) class Meta: model = Review fields = ('pk', 'title', 'user', 'movie', 'timestamp', 'review_text',) I have this viewset: class ReviewsViewSet(viewsets.ModelViewSet): queryset = Review.objects.all() serializer_class = ReviewSerializer and this model: class Review(models.Model): title = models.CharField(max_length=255) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='reviews') movie = models.ForeignKey(Movie, on_delete=models.CASCADE, related_name='reviews') review_text = models.TextField() timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return '{movie} review by {user}'.format(user=self.user, movie=self.movie) My javascript request looks like this: return axios({ method: 'post', url: 'http://localhost:8000/api/reviews/', data: { // Using data from Vue title: this.review_title, movie: this.id, review_text: this.review_text, user: JSON.stringify(this.user) }, headers: { 'Content-Type': 'application/json', Authorization: `JWT ${token}` } }) It gives me this traceback. How should I pass the user object to the request? Thanks in advance. -
Problem with the filter in the django-rest-framework
Im really confused. Why is this code not working ? class EduUserView(viewsets.ModelViewSet): serializer_class = EduuserSerializer def get_queryset(self): if(self.kwargs != {}): test = EduUser.objects.filter(eduId=self.kwargs['pk']) else: test = EduUser.objects.all() print(test) return test http_method_names = ['get'] Here you can see the console output -
AWS ElasticBeanStalk Django Application landing page error "Index of /"
I have faced a critical issue which goes as follows. there was an exception which was unhandled when that occurred AWS instance got terminated. and got landed to "Index of /" page tried to deploy the Django application again to EB, build and deployment was successful. but still seeing the "Index of /" page only. I am guessing the server stopped pointing to the application server and also believe this is something to do with the static files. I am using Jenkins to do the build and deployment process. has anyone faced this issue? enter image description here enter image description here -
Programmatically delete a Wagtail ListBlock item
I have an abstract class that defines a StreamField for a Wagtail Page: class DownloadGroupItem(models.Model): class Meta: abstract = True downloads = StreamField([ ('items', ListBlock( StructBlock( [ ('title', CharBlock()), ('description', TextBlock()), ('file', DocumentChooserBlock()), ], template='downloads/blocks/item.html', form_classname='downloads__itemlist struct-block' ), label='Add download' )) ]) If the file saved via the DocumentChooserBlock is deleted externally from the page, this makes the ListBlock item invalid to output in a template. If this occurs, the current behaviour is to leave the StructBlock with an empty - though required - value for file. I can mitigate this by adding a receiver for the Wagtail document model, and listening for models.signals.post_delete, but how can I programmatically delete the Wagtail ListBlock items that are affected? -
Benefit of NGINX reverse proxy for Python RESTful application
I have to deploy multiple Python applications. They have a common user interface that is built using React. They communicate with each other and the user interface using only REST i.e. there are no static files. I am using Gunicorn as the application server and Docker for isolating the applications. Currently, I have to deploy on a single machine for a limited set of users so there is not much need for load balancing. Is there any benefit of using Nginx as a reverse proxy for the above setup. And if the said benefit will persist in case different application share same Nginx server? -
using django compress with sass files
I already successfully configured django_sass_processor to generate and link scss files to one main css file. But because I also need to generate a main JS file from several others, I wanted to switch to django_compress, which in my understanding does the job as well for css/sass and for JS. But unfortunately I do not understand how to configure compress to compile the scss files. Do I need to add an extra precompiler like django-static-precompiler? Currently I have have setup compress as shown here: INSTALLED_APPS = [ ... 'compressor', ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'compressor.finders.CompressorFinder', ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') COMPRESS_ROOT = STATIC_ROOT COMPRESS_PRECOMPILERS = ( ('text/x-sass', 'sass --scss "{infile}" "{outfile}"'), ('text/x-scss', 'sass --scss "{infile}" "{outfile}"'), ) and in the test template I put {% load compress %} {% compress css %} <link href="main/styles/main.scss" rel="stylesheet" type="text/x-scss" /> {% endcompress %} But its not even working that compress is finding the file. I get the error 'main/styles/main.scss' isn't accessible via COMPRESS_URL ('/static/') and can't be compressed Unfortunately, in the compress documentation I can't find very much about sass compiling, except for the setting of COMPRESS_PRECOMPILERS -
django causing 403 forbidden error when i add csrf middleware
When i add CSRF middleware 'django.middleware.csrf.CsrfViewMiddleware' to prevent xss csrf attack i am getting error response 403 csrf error. i reffered official doc and old stack answers but still i didnt get any idea why it causing error. I read from django official doc if i added csrf middleware it will take care all csrf validation in every views by default. Along with this i have used some decorators too to ensure security like @login_required and @csrf_protect I'm newbie in Django so please don't down vote if my question is not a proper, instead please suggest correction and ask for clarifications. -
filter django serializer data
Many time we access data via serializer directory according to relationship defined in models in Django(1.11.10). How can i set a filter like fetch-only is_active=1. class DaasJobsSerializer(serializers.ModelSerializer): class Meta: model = DaasJobs fields = '__all__' class DaasScheduleSerializer(serializers.ModelSerializer): jobs = DaasJobsSerializer(read_only=True,many=True) class Meta: model = DaasSchedule fields = '__all__' Here i just want to set a filter to fetch only those Jobs which db field is_active=1 in this line like that DaasJobsSerializer(read_only=True,many=True, filter={"is_active":1}) how to do something like this ?? Currently it is giving me all the data without checking is_active, and i dont want to create serializerMethodField for that.. because all methods written earlier.. i am just setting a is_active field later in the tables in db. -
Django-Select2 jQuery conflict. on change select2 field not working with $
In my Django project, Select2 onchange function is not working with $. It's working with jQuery. I have all JS code with $ so I want to keep $ instead of JQuery. I am using Django-Select2==6.2.0 django-autocomplete-light==3.3.0 Django==2.1 Jquery Select2 4.0.3 This is how I want to do. var post_visible_to = $("#id_post_visible_to"); post_visible_to.change(set_post_visibility_cues); var set_post_visibility_cues = function() { ................... .................. } When I select an option from the field of select2 post_visible_to.change(set_post_visibility_cues) does not work. However if use jQuery like that var post_visible_to = jQuery("#id_post_visible_to"); it's working -
Nginx "X-Accel-Redirect" serves pdf at plaintext
I'm having a problem getting my pdf file to display on the browser using X-Accel-Redirect. Linking the file URL directly from Nginx public location works out fine. However, restricting access to the location by adding in "internal" and calling X-Accel-Redirect from Django's HttpResponse()sends the pdf file as plaintext, as it would any other static file (css, js, html). Python Response response = HttpResponse() response['Content-Type'] = 'application/pdf' response['Content-Disposition'] = 'attachment; filename=example.pdf' response['X-Accel-Redirect'] = '/media/file-pdf/example.pdf' return response Nginx Location location /media/{ internal; alias /var/www/media/; default_type application/pdf; } Javascript $.ajax({ url: http://www.example.com/pdf-api/, type: 'GET', success: function(data) { window.open(data); console.log(data); }, }); Sample pdf as text received (as seen on browser console) %PDF-1.3 %“Œ‹ž ReportLab Generated PDF document http://www.reportlab.com 1 0 obj << /F1 2 0 R >> endobj 2 0 obj << /BaseFont /Helvetica /Encoding /WinAnsiEncoding /Name /F1 /Subtype /Type1 /Type /Font >> endobj 3 0 obj << /Contents 7 0 R /MediaBox [ 0 0 595.2756 841.8898 ] /Parent 6 0 R /Resources << /Font 1 0 R /ProcSet [ /PDF /Text /ImageB /ImageC /ImageI ] >> /Rotate 0 /Trans << >> /Type /Page >> endobj 4 0 obj << /PageMode /UseNone /Pages 6 0 R /Type /Catalog >> endobj 5 0 … -
Login Page without Bultin Login System Django
I have a model called Van that have 2 fields: Plate and Password. I should use this informations to login in a frontend system (not django admin). Searching on the internet i just found example using Bultin Login System but i need a custom login using only Van model. Any suggestions?