Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django fetch dropdown data
How to fetch data from the database which just got stored in the DB. I have tried several attempts but got closer but still not a clean data which I would like to retrieve for the script to execute. MODEL: class CODE (models.Model): name = models.CharField(max_length=4, default=None) def __str__(self): return self.name class SiteData (models.Model): site = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) VIEW: def sitedata(request, *args, **kwargs): form = SiteData_Form(request.POST or None) template_name = 'sitedata.html' if request.method == 'POST': form = SiteData_Form(request.POST or None) if form.is_valid(): code_pk_list = request.POST.getlist('dc', None) selected_location = CODE.objects.filter(pk__in=code_pk_list) context = [{ 'location': selected_location, 'data1': request.POST['data1'], }] Location and data1 are dropdown selections.. I get the <QuerySet [<CODE: SITE1>]> How to get the only SITE1 thanks for the help In debug, i get ID not the text name. Location: `10` Data1: `1` -
serve existing excel files using django and pure javascript
Im trying to serve an existing excel file using django download it using javascript. I tried the following code in django view: Generate_Report is the io.Bytes() read from xlsxwriter. response=HttpResponse(Generate_Report.output,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition']='attachment;filename=Report.xlsx' return response In html I wrote this xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var downloadLink = window.document.createElement('a'); var contentTypeHeader = xhttp.getResponseHeader("Content-Type"); downloadLink.href = window.URL.createObjectURL(new Blob([xhttp.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})); downloadLink.download = "Report.xlsx"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } }; I want to serve an existing excel file as downloaded format. -
How to check for specific backend error keys when using async/await?
I want to display a custom message in Vue (with Django as the backend) when creating an account if the entered email already exists in the database. Currently the server returns a 400 with the following response: {"email":["There is another user with this email"]} How can I access this error object to check if it contains an "email" key? I've found this approach creating a wrapper: https://dev.to/sadarshannaiynar/capture-error-and-data-in-async-await-without-try-catch-1no2 but I feel like there must be a better/simpler way of handling this Last thing I tried: const { error, data } = await usersAPI.create(userData) where "create" is: create (data) { return Vue.axios.post(url, data, config) } then console.error(error) (but it doesn't print anything) -
How can I determine the separator when I got many inputs
I'd like to inform the value of two variables separated by an delimiter. Even thoug I can inform mutiple inputs, they will not be separateded. I get >>>>> 12 for example. I'd like >>>>> 1 2 x, y = input().split(' ') Actual result >>>>12 Expected >>>>> 1 2 -
Django - Html Audio Failed to load resource: the server responded with a status of 403 (Forbidden)
Audio file uploaded and referenced with the correct path, but does not play in html5 audio. models.py class AudioTrack(models.Model): track = models.FileField(upload_to=upload_image_path) index.html <audio controls> <source src="{{ instance.track.url }}"> <code>audio</code> element. </audio> The audio file get's stored together with the images in the media directory. I can download the file from the media directory. When I try to open the audio file path in a new tab I get a 403 Forbidden nginx/1.14.0 (Ubuntu) Ive also added the media context processor to the settings, but still the same. The HTML5 Audio player works with audio files from other websites. Thank you for any help -
Loading assets folder in Django
I recently started a basic django project, i want to load an already made default template. This template has an assets folder with all the CSS, JS files etc This folder, is later called in the templates, so for example i can have: <script src="./assets/somejsfile.js" type="text/javascript"></script> The problem with this is that none of the files in the assets are being retrieved. I know that the problem depends on where i put the assets folder, but i don't know how to solve that. I tried to add it to different parts of my project's structure but it doesn't work, since i only get a lot of errors like this: http://127.0.0.1:8000/assets/somecss.css net::ERR_ABORTED 404 (Not Found) Here is my settings.py: STATIC_URL = '/static/' In this static folder, there is a basic css file i tested before trying this. And here is the structure of my project: //MYSITE FOLDER migrations ASSETS templates -> INDEX.HTML (where the assets folder is called) views, forms etc -
Django Social Auth - Referring to usersocialauth for foreign key in model
I'm using the social_django package for the first time. The project only requires authentication for the application through Facebook so I implemented the SOCIAL_AUTH_FACEBOOK method into my app, which retrieves basic info like username, first name, last name, email address. I also get the user's Facebook profile picture through SOCIAL_AUTH_FACEBOOK_EXTRA_DATA. I want to figure out how to refer to the usersocialauth model as a parent key in my model. Right now, it's associating everything to auth_user model, which doesn't allow me to access the Facebook profile picture in the template. Here is what I am doing at the moment: models.py from social_django import models as oauth_models class Review(models.Model): ... author = models.ForeignKey(oauth_models.USER_MODEL, on_delete=models.CASCADE) I am able to access the basic fields in the template through <p>{{ review.author.name }}</p>, but to see the profile picture, I have to do something like this: {% for author in backends.associated %} <img src="{{ author.extra_data.picture.data.url }}" alt=""> {% endfor %} I would like to simplify this and just refer to the usersocialauth model so I can access all the data from one place in the template. -
Django - No 'Access-Control-Allow-Origin' header is present on the requested resource when making a POST
Whenever I make a request.post inside my custom authentication class, the response takes a while and then throws me this error (502) Access to XMLHttpRequest at 'http://54.185.235.97:8000/rest-auth/login/' from origin 'http://ec2-54-185-235-97.us-west-2.compute.amazonaws.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here is the code (This code send an email to the user to reset the password if he/she exceed the numbers of login attempts) headers = {'Access-Control-Allow-Origin': '*'} requests.post( "http://ec2-54-185-235-97.us-west-2.compute.amazonaws.com:8000/rest-auth/password/reset/", data={'email': user.email}, headers=headers ) user.is_blocked = True user.save() attemptsObject.delete() raise exceptions.AuthenticationFailed(('User Blocked')) This code works fine in my development workspace, but somehow gets trouble inside my AWS instance, is it something to do with my Nginx configuration? or do I need to create a Custom CORS middleware class? Nginx: upstream django_app { server unix:/var/www/backend/run/gunicorn.sock fail_timeout=10s; } server { listen 8000; server_name localhost; access_log /var/www/backend/logs/nginx-access.log; error_log /var/www/backend/logs/nginx-error.log warn; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django_app; } location ~* \.(eot|ttf|woff|woff2)$ { add_header Access-Control-Allow-Origin *; } } -
NoReverseMatch at / Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name
Hi i am beginner in django, I have started the course of it last week and got stuck into this error from last two days. Seeking for the help to get out from that mess i have made. I am not able to open the dashboard of my site don't know what has happened. I have been searching for this from last two days. Still doesn't got anything. Thanks in advance. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template C:\Users\kamal jeet singh\wproject\kt\webproject\Template\partials\_nav.html, error at line 50 Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name. 40 : 41 : <ul class="navbar-nav ml-auto"> 42 : {% if user.is_authenticated %} 43 : <li 44 : {% if 'dashboard' in request.path %} 45 : class="nav-item active mr-3" 46 : {% else %} 47 : class="nav-item mr-3" 48 : {% endif %} 49 : > 50 : <a class="nav-link" href=" {% url 'dashboard' %} "> 51 : Welcome {{ user.username }}, "Dashboard" </a> 52 : </li> 53 … -
Interactive WebAgg plot using Django Channels not rendering entire figure
I am trying to embed an interactive matplotlib plot using the WebAgg backend into a Django application. Whenever fig.canvas.draw() is called only parts of the figure are rendered in the browser. Versions: Python - 3.6.7 Django - 2.2.4 Channels - 2.2.0 Matplotlib - 3.1.1 I am using Django Channels for the figure's websocket. The figure has 3 points connected by two lines, the user can click and drag the points, after the user releases the mouse button the figure redraws the lines. The figure should draw the entire canvas on every 'motion_notify_event' and on 'button_release_event' before disconnecting the callback ids, but only seems to be drawing certain artists and doesn't even draw the x or y axis. I have been able to get this plot working in a Tornado web application. I've tried tracing the fig.canvas.draw call to see if the artists list is empty, but it wasn't. I think somehow the browser end of the figure is only rendering the differences. example.html: {% load staticfiles %} <html> <head> <script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js'></script> <link rel="stylesheet" href="{% static 'css/page.css' %}"> <link rel="stylesheet" href="{% static 'css/boilerplate.css' %}"> <link rel="stylesheet" href="{% static 'css/fbm.css' %}"> <link rel="stylesheet" href="{% static 'jquery-ui-1.12.1/jquery-ui.min.css' %}"> <script src="{% static 'jquery-ui-1.12.1/external/jquery/jquery.js' … -
No module named 'psycopg2.extensions' despite having 'psycopg2-binary'
I am trying to develop a Django project leveraging psycopg2 but when i deploy in a Docker container on python:3.7.4-slim I was running into the 'no pg_config' issue, so I determined the best way to proceed after some digging is to go with psycopg2-binary since since that seems to be the recommended way to go forward. Only problem now is that when I try to run the command python manage.py <...> from local I'm getting the error: ModuleNotFoundError: No module named 'psycopg2.extensions' I'm not sure how to proceed, since psycopg2 works fine locally but we are going to end up containerizing this resource and having it sit in a k8s cluster so I was fairly certain the binary library was the right way to go. Has anyone figured out a solution to pull in psycopg2.extensions without sacrificing the integrity of using the binary distribution? Happy to provide more context as-needed. Thanks! -
Django AudioFile OS Error: No such file or directory
I am trying to implement the audio field into my django project, but when I try to upload a file I get this OS Error. Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in change_view 1511. return self.changeform_view(request, object_id, form_url, extra_context) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view 1408. return self._changeform_view(request, object_id, form_url, extra_context) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in _changeform_view 1448. self.save_model(request, new_object, form, not add) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_model 979. obj.save() File "/usr/lib/python2.7/dist-packages/django/db/models/base.py" in save 808. force_update=force_update, update_fields=update_fields) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 848. update_fields=update_fields, raw=raw, using=using, File "/usr/lib/python2.7/dist-packages/django/dispatch/dispatcher.py" in send 193. for receiver in self._live_receivers(sender) File "/usr/local/lib/python2.7/dist-packages/audiofield/fields.py" in _rename_audio 222. os.rename(filename, dst_fullpath) Exception Type: OSError at /admin/products/product/20/change/ Exception Value: [Errno … -
Django ORM + Postgres + Enum Fields
(Django 2.2 + Latest Postgres) I am using Django Models with Enum Fields in this manner: from enum import Enum from django_enum_choices.fields import EnumChoiceField class DocumentType(Enum): SPREADSHEET = 'spreadsheet' PRESENTATION = 'presentation' In my Model class.... document_Type = EnumChoiceField(DocumentType, null=False) I migrate the model to Postgres, but I noticed there isn't any enum on the database side field definition. I could easily break the constraints of the enum by entering data directly into the DB via a query in an external tool like DataGrip. Isn't there any component that'll constrain the database as well to the enum i declared in my model? -
python: logging: can we added multiple filters to the logger and which one is considered
I am trying to understand how multiple Filters (one defined in config and other in the code) in Python logging work. I am working on a Django project and below is my logger config in settings.py My goal is to switch on and switch off the logger whenever i want. So using filters i am trying to switch off the logger by returning False (0) 1) Switch off the logger in the starting class StartFilter(object): def filter(self, record): """ Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ return 0 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'formatter': 'verbose', 'class': 'logging.StreamHandler', }, }, 'filters': { 'myfilter': { '()': StartFilter, } }, 'loggers': { 'log_testing': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, 'filters': ['myfilter'] }, } } I have added the filter to the logger. 'filters': ['myfilter'] 2) Switch on and off the logger in the views.py file where i want the logging to be seen # to switch … -
Initial value not showing up in DecimalField
I have a form with a DecimalField and I have set the initial value like so: class RawProductForm(forms.Form): title = forms.CharField(label="") description = forms.CharField(required=False) price = forms.DecimalField(initial=199.99) However, the initial value is not showing up when I render the page: What could be the issue? -
Form variables inside templates
As far as I know in Django, if I want to pass the form variable inside the templates I use the {{ form }} tag. But in the code that I am following they put the variable as {{ answer_form }}. How is this all working, and would replacing the latter with form work? views.py class CreateAnswerView(LoginRequiredMixin, CreateView): form_class = AnswerForm template_name = 'qanda/create_answer.html' def get_initial(self): return { 'user': self.request.user.id, 'question': self.get_question().id, } def get_context_data(self, **kwargs): return super().get_context_data(question=self.get_question(), **kwargs) def get_success_url(self, form): return self.object.question.get_absloute_url() def form_valid(self, form): action = self.request.POST.get('action') if action =='SAVE': #save and redirect as usual return super().form_valid(form) elif action == 'PREVIEW': ctx = self.get_context_data(preview=form.cleaned_data['answer']) return self.render_to_response(context=ctx) return HttpResponseBadRequest() def get_question(self): return Question.objects.get(pk=self.kwargs['pk']) Part of the HTML(post_answer.html) <div class="col-sm-12" > <h3 >Post your answer</h3 > <form method="post" action="{% url "qanda:answer_question" pk=question.id %}" > {{ answer_form | crispy }} {% csrf_token %} <button class="btn btn-primary" type="submit" name="action" value="PREVIEW" >Preview </button > <button class="btn btn-primary" type="submit" name="action" value="SAVE" >Answer </button > </form > </div > -
How to fix "Django form validation unit test returns False value"
I have to customize a form, and had to add 4 drop-down to the existing form. Before adding the drop downs, my unit test cases form validation function returned “True” value. But after adding the drop-downs the function is returning “False”. I am not sure what exactly is the problem, can any one help me what is the exact issue. I use below function for unit testing... Form validation unit test function test.py: def test_form_is_valid(self): form = self.form_class(data=self.data, **self.get_form_kwargs()) self.assertTrue(form.is_valid()) My customize drop-down is below... <div class="col-md-6"> <div class="form-group"> <label class="control-label" for="id_management_fund_income">Management Fund Account *</label> <select name="management_fund_income" title="" required="" class="form-control" id="id_management_fund_income"> <option value="">---------</option> {% for mf in managementaccountlist %} <option value="{{ mf.pk }}" {% if mf.pk == setting_data.management_fund_income_id %}selected="selected" {% endif %}>{{ mf.code }}-{{ mf.name }}</option> {% endfor %} </select> </div> </div> My whole template(template.py) file is below... {% load bootstrap3 %} {% load tags %} <div class="ibox"> <div class="ibox-title"> <h5>Maintenance Invoicing Settings</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="ibox-content"> <div class="row"> <div class="col-md-8"> <div class="row"> <div class="col-md-6"> {% bootstrap_field form.management_fee addon_before="$" %} </div> <div class="col-md-6"> {% bootstrap_field form.sinking_fund_contribution addon_before="$" %} </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label" for="id_management_fund_income">Management Fund Account *</label> <select name="management_fund_income" title="" … -
Django: 'SafeText' object has no attribute 'as_widget'
In my django template form this works {{ form.content_previeiw.as_hidden }} But this gives error {{ form.content_previeiw.as_hidden|add_class:"post_content_previeiw" }} Error: 'SafeText' object has no attribute 'as_widget' What am I doing wrong? And how to solve it? -
how to construct condition in ValidationError
I have a model named Comments which has content=models.CharField(max_length=100) in forms I want to use "def clean_content" to raise validation error if user types characters exceeding max_length. So how to use if condition operator. def clean_content(self): content = self.cleaned_data.get("content") if ????????? < 100: return content else: raise forms.ValidationError(('You exceeded max number of character')) -
Using .ttf font file in Pillow within a django app hosted on Heroku
I am setting up my first web application via the Django framework. This application takes data supplied by an html form and generates an image using Pillow. this image features text drawn on top of it, and I would like to use a particular .ttf file when generating the text. The font is used just fine when I run the app locally (via manage.py runserver), however, when running on Heroku an "OSError" occurs as it "cannot open resource". Location of font file in directories. scales is the Django root folder. scales1 is a package I wrote containing image generation logic. The scales_app folder contains the view for which the image is generated. scales/AGENCYB.ttf scales/scales1/AGENCYB.ttf scales/static/fonts/AGENCYB.ttf scales/scales_app/AGENCYB.ttf The Heroku app builds just fine and can be visited via web browser. https://guit-proj-1.herokuapp.com/scales/SelectBoard Clicking the "Gen Board" button will elicit the traceback below. Note that the application was fully functional when the default font for pillow was used. However, the font did not look acceptable for my application. I have tried placing the font file in all places where it might be relevant including the root directory of the Django app, the python package where the image generation logic is stored, and in … -
Validating a modelformset with a restricted queryset
I'm trying to validate a modelformset with a queryset filtered on one field having a specific value, where any added forms need to have that specific value set. I'm a relative beginner with Django and hoping there will be a 'standard' answer to my requirement, which I feel can't be that unusual. I have three models (for the purposes of this question) - Project, Stage and Check. The constraint is that there may only be at most one Check for each combination of Project and Stage. At the model level this is met by: class Meta: constraints = [models.UniqueConstraint(fields=['project', 'stage'], name="project-stage"),] where project and stage are ForeignKey fields in the Check model, and this works. I have a view with a modelformset that shows all Checks for a given Project. The view queryset is models.Check.objects.filter(project__id=pk) where pk is an integer from the url (eg project/1/). In the ModelForms, the project field is excluded because it's fixed and the user doesn't need to see it in each form. Thus it's not available in the form data, cleaned or otherwise, and I have to insert it myself. I'm inserting the correct value for project_id in the view: if request.method == 'POST': formset … -
Wagtail orderable is null in parent
I want to add gallery page (with slider as preview in parent) to my wagtail blog. Here's code: # Gallery page, preview of this page will be displayed as slider class GalleryPage(Page): # label = "Heading, tags and categories will be auto-inserted" body = StreamField([ ('paragraph', blocks.RichTextBlock(label = "Paragraph")), ]) content_panels = Page.content_panels + [ StreamFieldPanel('body'), InlinePanel('gallery_images', label = "Images that will be displayed on this page"), ] # Every image in gallery will be instance of this class class GalleryImage(Orderable): page = ParentalKey(GalleryPage, on_delete=models.CASCADE, related_name='gallery_images') image = models.ForeignKey( 'wagtailimages.Image', on_delete=models.CASCADE, related_name='+' ) # If true, image will be used in slider in parent page ShowInSlider = models.BooleanField(null=True, blank=True) panels = [ MultiFieldPanel([ ImageChooserPanel('image'), FieldPanel('ShowInSlider', widget=forms.CheckboxInput()), ]) ] # Standard blog page with text/images etc. class BlogPage(Page): # Fields panels etc # This function should return images that will be displayed in parent page as slides. def get_context(self, request): context = super(BlogPage, self).get_context(request) context['slider_images'] = self.get_children().specific()[0].FIELD_THAT_I_WANT print(context['slider_images']) return context And almost everything works as excepted, I can read title and body (for example) using this line: print(context['slider_images']). But, if i want to request for gallery_images, prints blog.GalleryImage.None. I had done similiar thing in my last project, and it worked. I … -
How to set permissions to only POST data for API (React + Django Rest Framework)
I'm writing my blog with React as Frontend and DRF as a backend. I've made two API's - one is made for posts and second one is made for data contained in Contact Form. To obtain posts I'm using axios and the Django permission is set to IsAdmin - it means only admin can change post and this is fine. The second one is a problem - if I change a permission to AllowAny it causes that Anonymous user can POST their data and... they can view it. If I change it to IsAdminUser none of users can POST their data. I need to know how I can store people's data safe (they can only POST data, and they are NOT allowed to view my API for contact form.) Contact.js const Contact = () => { return ( <section> <Formik validate initialValues={{ firstName: "", email: "", }} onSubmit={values => { setTimeout(() => { axios .post("http://127.0.0.1:8000/api/questions/", values) .then(res => { alert("Sent", res.data); }) .catch(err => { alert(err); }); // console.log(JSON.stringify(values, null, 2)); }, 500); }} render={() => ( <Form> <label htmlFor="firstName">Name</label> <Field name="firstName" placeholder="Name" required /> <label htmlFor="email">Email</label> <Field name="email" placeholder="email@acme.com" type="email" required /> <button type="submit">Submit</button> </Form> )} /> </section> ); … -
Django queryset interpolation for a previous / next instance function
Writing a dry function that returns either previous or next instances of a given instance. This function return previous instances: def previous(instance): try: return Picture.objects.filter(id__lt=instance.id).first() except Picture.DoesNotExist: return instance I want to create an abstracted function which returns either the previous or the next instance using an additional gt_or_lt argument. The problem lies in interpolating that argument into the filter(id__gt_or_lt). def seek_instance(gt_or_lt, instance): try: return Picture.objects.filter(id__gt_or_lt=instance.id).first() except Picture.DoesNotExist: return instance I've tried: return Picture.objects.filter(id__gt_or_lt = instance.id).first() seek_instance("gt", instance) return Picture.objects.filter(id__f"{gt_or_lt}" = instance.id).first() seek_instance("gt", instance) return Picture.objects.filter(f"{gt_or_lt}" = instance.id).first() return Picture.objects.filter(gt_or_lt = instance.id).first() seek("id__gt", instance) All fail with their respective errors. -
Django authentication using windows credentials
I want to make my app who its made in Django + Rest framework and front-end in React to login automatically using the domain active directory. I searched on the internet but I don`t find a complete solution how to do it. From what I read over the internet I need to config the Apache server and in django back-end to use python-ldap or something like this. Can anyone have a link or something or a solution? Thanks and sorry for my english !