Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
React JS Frontend with DRF backend authentication
Have developed a pretty decent API utilizing Django and Django Rest Framework to make my data available for consumption. Decided to build a React JS front end to be a little more dynamic than the standard Django templates. I have numerous views within DRF which work fine, I'm able to make calls against them and get or post to them no problem. Currently I'm working on implementing a login capability for the React frontend so that users will be given access to a couple protected views and will be presented with information relevant to them. Maybe I'm not understanding what is supposed to be happening, web development isn't exactly my area of expertise. Have referenced the Django documentation a bunch trying to understand sessions and session authentication. I have a 'login' view which is taking a username and password provided to it, searching for a related 'User' record based off of the username and attempting to leverage the django.contrib.auth login method; this all seems to be working, the user is getting authenticated. After this step, I'm pretty much completely lost as to what is supposed to happen. In my React component, I've attempted sending the username as a 'session' attribute … -
Django-Tenants Search Among All Schemas from a public Schema
I am using Django-tenants and was wondering how to access/search among all schemas ? Is it possible? Whats the best approach? Any hints or links to resources will be much appreciated. -
django file upload error The 'image' attribute has no file associated with it
I getting error after the file upload with dropzone. I guess due to file is not uploaded. ValueError at /ui/project_detail/4/ The 'image' attribute has no file associated with it. my view function snippet: @csrf_exempt def project_image_alternative_form_submit_ajax(request, object_id): project_image = ProjectImage.objects.filter(pk=object_id).first() if not project_image: response_json = { 'message': 'Image you provided pk for doesnt exist!', } return JsonResponse(response_json, status=status.HTTP_400_BAD_REQUEST) if request.method == 'POST': if request.is_ajax(): image_file = request.FILES.get('image_file') project_image_alternative = ProjectImageAlternative( project_image=project_image, image=image_file, ) project_image_alternative.save() response_json = { 'message': 'Alternative Image saved successfully!', 'image_alternative_pk': project_image_alternative.pk } return JsonResponse(response_json, status=status.HTTP_200_OK) else: response_json = { 'message': 'Please send a POST request', } return JsonResponse(response_json, status=status.HTTP_400_BAD_REQUEST) return JsonResponse(response_json, status=status.HTTP_200_OK) my dropzone function snippet: $('.alternative_image_upload').dropzone({ maxFiles: 1, autoProcessQueue: true, parallelUploads: 1, headers: { 'Cache-Control': null, 'X-Requested-With': null, }, error: function(file, response, xhr) { if (typeof xhr !== 'undefined') { this.defaultOptions.error(file, xhr.statusText);// use xhr err (from server) } else { this.defaultOptions.error(file, response);// use default (from dropzone) } }, sending: function(file, xhr, formData) { var pk = this.element.dataset['pk']; formData.append('pk', pk); }, init: function() { this.on("success", function(file, response) { console.log(response); }); }, uploadMultiple: false, acceptedFiles: '.jpg, .jpeg, .png, .svg' }) -
Django - Temporary midi file
Sorry if I'm not getting something right, I am new to web application development, I've been working on a project with Django and I wish I could do the following: When the user clicks on a button an Ajax request is generated (I am using plain Javascript). This request sends some notes to the server (Django) that generates a melody. The server saves the melody in a midi file that I want the user to be able to listen to in the front-end like this: <midi-player src = "url/path/to/temporaryfile" sound-font visualizer = "#myVisualizer"> </midi-player> <midi-visualizer type = "staff" id = "myVisualizer"> </midi-visualizer> I want this file to be temporary so that it does not take up space, that is, that the user can listen to the melody, have the option to download it, etc, but that when they leave the page, the file is deleted and thus does not take up more space . Is this the best way to do what I think? -
Fetch all Django objects that have a M2M relationship
I have the following two Django models: class Parent(models.Model): name = models.CharField(max_length=50) children = models.ManyToManyField("Child", through="ParentChild") def __str__(self): return self.name class Child(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name Let's say I have four Parent objects in my database, only two of which have children: for parent in Parent.objects.all(): print(parent, parent.children.count()) # Parent1 3 # Parent2 0 # Parent3 0 # Parent4 1 My goal is to write an efficient database query to fetch all parents that have at least one child. In reality, I have millions of objects so I need this to be as efficient as possible. So far, I've come up with the following solutions: Using prefetch_related for parent in Parent.objects.prefetch_related("children"): if parent.children.exists(): print(parent) # Parent1 # Parent4 Using filter: for parent in Parent.objects.filter(children__isnull=False).distinct(): print(parent) # Parent1 # Parent4 Using exclude: for parent in Parent.objects.exclude(children__isnull=True): print(parent) # Parent1 # Parent4 Using annotate and exclude: for parent in Parent.objects.annotate(children_count=Count("children")).exclude(children_count=0): print(parent) # Parent1 # Parent4 Which of these solutions is the fastest? Is there another approach that's even faster / more readable? I'm seeing a django Exists function but it doesn't appear to be applicable for this use case. -
data by dynamically generating time periods
I am making an employee time tracker, the problem I have is logic for a payday that is every other Friday (every 2nd Friday also known as bi-weekly) so the dates change. Came across this code but can't make sense of all of it, can anyone please help explain it, looks like some I can use or get inspired from. Thanks. def get_metrics(self, frequency): select_fields = OrderedDict() if frequency == 'week': select_fields['time_period'] = "date_trunc(%s, initial_timestamp::TIMESTAMP WITH TIME ZONE AT TIME ZONE %s + '1 day'::interval) - '1 day'::interval" else: select_fields['time_period'] = "date_trunc(%s, initial_timestamp::TIMESTAMP WITH TIME ZONE AT TIME ZONE %s)" select_params = (frequency, settings.TIME_ZONE,) queryset = self.extra(select=select_fields, select_params=select_params ).values('time_period', ....) queryset = queryset.annotate(# Add annotations ) return queryset SOURCE -
Stripe connect integration with Django
I'm new integrating stripe in django but lately, I've been having an error that I just can't find the answer to it, every time that I try to connect the stripe account to my website, this error appears: {"error":{"message":"No application matches the supplied client identifier"}} Here's the code: import urllib import requests from django.urls import reverse from django.http import HttpResponseRedirect from django.views import View from django.conf import settings from django.shortcuts import redirect from .models import Seller class StripeAuthorizeView(View): def get(self, request): if not self.request.user.is_authenticated: return HttpResponseRedirect(reverse('login')) url = 'https://connect.stripe.com/oauth/authorize' params = { 'response_type': 'code', 'scope': 'read_write', 'client_id': settings.STRIPE_CONNECT_CLIENT_ID, 'redirect_uri': f'http://localhost:8000/users/oauth/callback' } url = f'{url}?{urllib.parse.urlencode(params)}' return redirect(url) class StripeAuthorizeCallbackView(View): def get(self, request): code = request.GET.get('code') if code: data = { 'client_secret': settings.STRIPE_SECRET_KEY, 'grant_type': 'authorization_code', 'client_id': settings.STRIPE_CONNECT_CLIENT_ID, 'code': code } url = 'https://connect.stripe.com/oauth/token' resp = requests.post(url, params=data) # add stripe info to the seller stripe_user_id = resp.json()['stripe_user_id'] stripe_access_token = resp.json()['access_token'] seller = Seller.objects.filter(user_id=self.request.user.id).first() seller.stripe_access_token = stripe_access_token seller.stripe_user_id = stripe_user_id seller.save() url = reverse('home') response = redirect(url) return response settings.py STRIPE_PUBLISHABLE_KEY = '<your test publishable key here>' STRIPE_SECRET_KEY = '<your test secret key here>' STRIPE_CONNECT_CLIENT_ID = '<your test connect client id here>' -
Get Different Responses from Async Call
I have a function in my react app that sends data to my Django API. Once that data is received, django calls an external python function to execute some code. Currently I have the javascript give me an alert when it receives an ok response. However, Django isn't sending this response until the external function completes; this is a problem because the external function can take up to an hour to run based on the user's input. Can this be changed to give one alert once the external python code begins to successfully run and a second time when the function is complete? I understand their can be a failure when sending the data to the API, the API not being able to access the data possibly because of a mismatched data type, and finally if the data is incompatible with the external function. I am looking for 3 different responses from the async function React export const SendData = (url, props) =>{ //this url is the url to the DataInput api view const data1 = document.getElementById('data1') const data2 = document.getElementById('data2') async function postData() { var res = '' const options ={ method : 'POST', headers: { 'Accept': 'application/json', 'Content-Type': … -
Different Field types of model class
I'm trying to provide for users possibility to store in SomeModel a list of ExtraParameters of any number or kind (it may be something small like IntegerField, BooleanField or quite large like TextField). I tried to implement ExtraParameter abstract model class, that will keep ForeignKey to SomeModel, and also its child classes with only one parameter like: class ExtraParameter(models.Model): somemodel = models.ForeignKey(SomeModel, ...) class Meta: abstract = True class IntegerExtraParameter(ExtraParameter): value = models.IntegerField() I believe it takes multiple small classes like this one so it could be migrated to multiple database tables of different fields. Am I right? Please provide better solution. Maybe other way to decorate ExtraParameter is possible? The problem with this approach is while implementing template it is not so easy to get all the stored parameters of all kind by doing somemodel.extraparameters.all(), rather I need to call every child class explicitly and build set from it. But also I've seen a solution with finding all subclasses of any class inside app's config, so it would help. Jakub -
Django CMS CSS styling
so I’m working with Django and I’m trying to figure out how in the edit the CSS using nothing but Django CMS? Is there a way? Anything would be helpful. -
What is the best way to include an error message?
I'm creating an auction site and I want the code to return an error message and send the user back to the index page if the bid is too low. What's the best way to include this? I'm new to Python and Django. I want the else statement to be the error message reroute to index. Thanks! if(newBid > price): query2 = NewPost.objects.filter(title = title).update(price = newBid) new = Bid.objects.create(itemID = itemID, newBid = newBid, highestBidder = username) new.save() return render(request, "auctions/index.html") else: return render(request, "auctions/index.html") -
Running Django checks in production runtime
I have a Django app that is deployed on kubernetes. The container also has a mount to a persistent volume containing some files that are needed for operation. I want to have a check that will check that the files are there and accessible during runtime everytime a pod starts. The Django documentation recommends against running checks in production (the app runs in uwsgi), and because the files are only available in the production environment, the check will fail when unit tested. What would be an acceptable process for executing the checks in production? -
nginx/django/uwsgi X-Accel-Redirect not working
I've seen a few similar posts, but no solutions proposed. My situation's slightly different, so some people may see the cause of the problem. I'm trying to migrate a django app from one server (python2.7, django 1.11, nginx 1.10.3, uwsgi 2.0.9) to a new server (python 3.6, django 2.2.2, nginx 1.16.1, uwsgi 2.0.19) and have problems with protected files. Here are some relevant codes. # app.settings.py ... PROTECTED_ROOT = '/data/app/protected') # just hard coded here to simplify # urls.py from app.views import protected_file ... urlpatterns = [ ... path('protected/<slug:lab>/<slug:project>/<path:path>/', protected_file, name='protected'), ] # app.views.py from django.http import HttpResponse from django.conf import settings ... def protected_file(request, lab, project, path): file = os.path.join(settings.PROTECTED_ROOT, lab, project, path) # after do some checking on file response = HttpResponse() response['Content-Type'] = 'text/plain' response['X-Accel-Redirect'] = '{0}/{1}/{2}/{3}'.format('/protected', lab, project, path) # print(response['X-Accel-Redirect'], file=sys.error) showed correct content return response # nginx.conf http { ... upstream django { server unix:///data/app/uwsgi.sock; # for communication with uwsgi } server { ... location /protected/ { internal; alias /data/app/protected/; } } There were no errors when I started nginx and uwsgi and all other functions were working, but when I tried to access the protected files (such as http://hostname/protected/lab/project/test.txt), nginx kept sending requests … -
Difference between reverse and lazy_reverse?
I read more projects in Django however I didn't understand! class SignUpView(generic.CreateView): form_class = UserCreationForm success_url = reverse_lazy('login') template_name = 'signup.html' like this -
Display multiple forms on one page with colliding field names
I need to have 2 forms on the same page that both have the field email and are both submitted at the same time: Person form that has the email field: class PersonForm(forms.ModelForm): class Meta: model = Person fields = [ 'first_name', 'last_name', 'email' ] And an organization form, which also has the email field: class OrganisationForm(forms.ModelForm): class Meta: model = Organisation fields = [ 'name', 'url', 'email', ] However, the request.POST.email will obviously always have the last displayed form's value, overwriting the first value. Is there a way to deal with this, like if we renamed the organisation's email as organisation_email? fields = [ 'name', 'url', 'email AS organisation_email', ] without having to define in OrganisationForm a custom field: org_email = models.EmailField(max_length=4096, blank=True, db_index=True) and have to overwrite the save() method? Plus, I don't like having to redefine the max_length and blank properties in case they change in the original Model. -
Change the default message in django-admin when deleting
I have a model where a user can add some data and assign this data to a specific month. But if that user had already added some items and try to delete a specific data who is assigned to a previous month it should be locked. I had success with this, but my problem now is with the message for the user. I would like to remove the default message of the delete button on admin but until now without success. Here is the image of the problem: MessageImage admin.py class MontlyReleaseAdmin(admin.ModelAdmin): form = MontlyReleaseForm def get_actions(self, request): actions = super().get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions def delete_model(self, request, obj): if not is_valid_date(obj): messages.add_message(request, messages.ERROR, 'Not Deleted') else: super().delete_model(request, obj) admin.site.register(MontlyRelease, MontlyReleaseAdmin) -
How should I go about integrating wagtail-lazyimages with Wagtail's RichTextField?
I'm trying to implement lazy loading for my blog post images, but I'm utilizing RichTextField for my blog posts, so I'm unable to specify each image tag like the Wagtail-LazyImages documentation suggets I should. According to the Wagtail Docs on RichTextField internals, an image may be stored as <embed embedtype="image" id="10" alt="A pied wagtail" format="left" /> but upon rendering is translated to <img alt="A pied wagtail" class="richtext-image left" height="294" src="/media/images/pied-wagtail.width-500_ENyKffb.jpg" width="500"> meaning there's not every any explicit tag usage like LazyImages is looking for. This is more of a conceptual question, as I'm just not sure where in the process to hook into Wagtail's RTF processing. Could I utilize the register_rich_text_features hook to make a new "feature" for lazy images that will then use the lazyimages class? -
Django Connect To MySql DB Table
I'm trying to Make an auth system without using the Django user.authenticate system because I want to make 2 seperate Login Systems. 1 For the IT & Web Development Dept. and another 1 for the general users. So I'm using the same MySql Database and the Auth_user for my IT dept. and I created a accounts app which I want to use the accounts_benutzer (users in german) table. I can add thanks to the app system users etc. over the Admin Panel but I want that the users which are registered by an IT Dept User log in on the Main Page with the given username and password My views/models/template is like: accounts/models.py: class Benutzer(models.Model): regex = RegexValidator(regex=r'^\+?1?\d{7,15}$') name = models.CharField(max_length=100) passwort = models.CharField(max_length=32) email = models.EmailField(max_length=254) .... accounts/views.py : from django.shortcuts import redirect, render from django.contrib import messages from django.contrib.auth.models import User, auth from .models import Benutzer def login(request): if request.method == 'POST': username = request.POST['name'] passwort = request.POST['passwort'] if (username == Benutzer.name) and (passwort == Benutzer.passwort): return redirect('/') else: messages.info(request,'Falsche Zugangs Daten!') return redirect('/accounts/login') else: return render(request, 'login.html') login.html: {% load static %} <form action="login" method="post"> {% csrf_token %} <p>Benutzername: <input type="text" name="name" placeholder="Benutzer Name"></p> <p>Passwort: <input type="password" … -
Django + Angular authentication fails when Django hosts page. Works on separate servers
I have a web application using Django as the backend and Angular for the frontend. I have implemented TokenAuthentification which works fine when I am using ng serve --poll 2000 and python manage.py runserver but when I use Apache2 + wsgi_mod to run the Django project with Angular built with node --max_old_space_size=5048 ./node_modules/@angular/cli/bin/ng build --prod --aot --output-path ../backend/static/ang --output-hashing none and loaded in the index.html. The page renders fine, and collects data from the DB (provided no auth is required for that page) but when I'm looking for user specific data and use request.user its not available. Looking at the headers the Authorization header is still being sent but in my Django code the user is unauthenticated. I have spent ages on this and can't figure out why the request is being treated differently. Any advice? -
Django server reporting "Forbidden (CSRF token missing or incorrect.)" despite sending token correctly?
I am trying to send a JSON POST request to my Django server. It reports this error: Forbidden (CSRF token missing or incorrect.): In my Django template, options.html, I say this: <script>const incomingToken = "{{ csrf_token }}";</script> And this: <input type="hidden" name="csrf-token" id="csrf-token" value="{{ csrf_token }}" /> Then in my JavaScript file that runs in the client I say: const serverUrl = "http://127.0.0.1:8000/" const headers = new Headers({ 'Accept': 'application/json', // 'X-CSRFToken': getCookie("CSRF-TOKEN") "X-CSRFToken": document.getElementById("csrf-token").value }) fetch(serverUrl, { method: "POST", headers: { headers }, mode: "same-origin", body: JSON.stringify(editorState.expirationDate, editorState.contracts, editorState.theta) // FIXME: server goes "Forbidden (CSRF token missing or incorrect.)" and 403's }).then(response => { console.log(incomingToken) console.log(document.getElementById("csrf-token").value) console.log(response) }).catch(err => { console.log(err) }); Both incomingToken and document.getElementById("csrf-token").value report the same value. So I know I'm getting the correct string for the CSRF token. How can this be? What am I doing wrong? For reference, here is what I see in another thread on the subject: const csrfToken = getCookie('CSRF-TOKEN'); const headers = new Headers({ 'Content-Type': 'x-www-form-urlencoded', 'X-CSRF-TOKEN': csrfToken }); return this.fetcher(url, { method: 'POST', headers, credentials: 'include', body: JSON.stringify({ email: 'test@example.com', password: 'password' }) }); Instead of running a function to retrieve the value from a cookie, I simply insert … -
How to show fields of a model in django?
Suppose I have a situation where I input a field from user and depending upon the field I have to query the corresponding model. Say if the user enters rice then I have to query on rice model. Also there are many models where each models have different number of fields.. What I want is to return a list containing n number of dictionary where n is the number of fields in that model. Say if I have username and age fields in student model then I want to return [{"username":"Sagar"},{"age":21}]. Any suggestion on how to achieve this. -
How to properly add multi choice field to existing form in Django?
Just like in title. This is what I currently have. I've tried django-multiselectfield but I had many issues with my foreignkey and ManyToMany usage in models. Maybe I should just use a JavaScript or something? I'm a newbie to Django and I really don't know which way to take. MODELS class Category(models.Model): name = models.CharField(max_length=50, unique=True) def __str__(self): return f'{self.name}' class Expense(models.Model): class Meta: ordering = ('date', '-pk') category = models.ForeignKey(Category, null=True,blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=50) amount = models.DecimalField(max_digits=8,decimal_places=2) date = models.DateField(default=datetime.date.today,db_index=True) def __str__(self): return f'{self.date} {self.name} {self.amount}' FORMS class ExpenseSearchForm(forms.ModelForm): GROUPING_CHOICES = ('date', 'category asc', 'category desc') grouping = forms.ChoiceField(choices=[('', '')] + list(zip(GROUPING_CHOICES, GROUPING_CHOICES))) SORTING_CHOICES = ('date asc', 'date desc' ) sorting = forms.ChoiceField(choices=[('', '')] + list(zip(SORTING_CHOICES, SORTING_CHOICES))) class Meta: model = Expense fields = ('name','category') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for i in self.fields: self.fields[i].required = False -
Is there a way in Django to filter through choices?
There's a field in Django called choices, where you can fill out 'choices'. ''' connector = models.CharField( max_length=255, null=True, blank=True, choices = Food, verbose_name="food", Food = [ ('chicken', 'Chicken'), ('queso', 'Queso'), ('carne', 'Carne') ] ''' Like that for example. But what if the list of choices is much, much larger than just 3? Is there a way to add a searching functionality so that it can narrow it down? Like an autocomplete? I have a list of over 300 items that I want as choices, but I only want them to show when I type the relevant letters - i.e. I type "A" I'd like a dropdown list of the choices that start with A. Is there a way to do this easily within Django? -
ValueError: too many values to unpack (expected 2) returning from function
I am returning two values from a function, however, I am unable to unpack them. My first function returns: return ("Fail", image_url) When I try to retrieve the values via; result, screen_url = test.test_signin(email, password, exp) I am getting a "too many values to unpack error". I have tried running the code without the () in the return statement. I get the same error. -
Django form POST resulting in 404
I am attempting to take in a form for update or delete, run the process and either return the updated url, or the updated list of objects. I've got the dynamic url building working, but when I hit submit I get a 404. I am struggling with the how to process the POST, as it doesn't even seem to be hitting that far in the code. Code below: urls.py path("customers/", views.customers, name="customers"), path("customers/customer/<int:id>/", views.customer), forms.py class CustomerMaintForm(ModelForm): class Meta: model = AppCustomerCst fields = ('id_cst', 'is_active_cst', 'name_cst', 'address_1_cst', 'address_2_cst', 'address_3_cst', 'city_cst', 'state_cst', 'zip_cst', 'country_cst', 'salesrep_cst', 'type_cst', 'is_allowed_flat_cst', 'iddef_cst', 'date_created_cst', 'date_suspended_cst', 'date_first_tran_cst', 'date_last_tran_cst', 'is_credit_hold_cst', 'old_balance_cst', 'balance_notify_cst', 'balance_statement_cst', 'balance_conversion_cst', 'balance_cst', 'receive_emails_cst', 'contact_domain_cst' ) labels = {'id_cst': 'Customer ID', 'is_active_cst': 'Active?', 'name_cst': mark_safe('<p>Name'), 'address_1_cst': 'Address 1', 'address_2_cst': 'Address 2', 'address_3_cst': 'Address 3', 'city_cst': 'City', 'state_cst': 'State', 'zip_cst': 'Zip', 'country_cst': 'Country', 'salesrep_cst': 'Sales Rep', 'type_cst': 'Type', 'is_allowed_flat_cst': 'Allowed Flat?', 'iddef_cst': mark_safe('<p>Id'), 'date_created_cst': 'Created Date', 'date_suspended_cst': 'Suspended Date', 'date_first_tran_cst': 'First Tran Date', 'date_last_tran_cst': 'Last Tran Date', 'is_credit_hold_cst': 'Credit Hold?', 'old_balance_cst': 'Old Balance', 'balance_notify_cst': 'Balance Notify', 'balance_statement_cst': 'Balance Statement', 'balance_conversion_cst': 'Balance Conversion', 'balance_cst': 'Current Balance', 'receive_emails_cst': 'Receive Emails?', 'contact_domain_cst': mark_safe('<p>Contact Domain')} views.py def customer(request, id): if request.method == "GET": obj = AppCustomerCst.objects.get(id_cst=id) instance = get_object_or_404(AppCustomerCst, id_cst=id) …