Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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) … -
Django does not create object in the database during pytest run
I am having weird issue with objects not being saved into database during test run. Code sample: @pytest.mark.django_db class TestCosts(TestCase): def setUp(self): self.account = mixer.blend(Account) acc_settings = Settings.objects.create( account=self.account ) print(acc_settings.id) all_settings = Settings.objects.all() print(len(all_settings)) Weird thing is that running this test suite standalone works correctly, but when running all tests this always failed(Printed length is always zero even though printed id is correct). Unfortunately I am not able to build minimal reproducible example. Is there any known reason this could happen? How can I debug this issue? This started to happen after I have migrated Django from 2.2 to 3.1 and pytest from 2.7 to 4.0 -
How to add a progress bar which keeps track of student completion of courses in a Django LMS
I'm new to Django and have a running e-learning(Learning Management System) website in Django where students can view contents uploaded by Instructors but i would like to add a progress bar which keeps track of the modules completed by students in the form of checkboxes and automatic checking of boxes if the student spends more than a minimum number of minutes (if possible). Models.py file with course and modules model Views.py file from the students app Student Course Detail Template -
Save two model (One contains foreign key) data from a single template
I'm pretty new to django and working on a blog based project where user can add ratings to specific type of review post.For example giving stars are enabled for restaurant but not for tech stores. I have created two different form for "review" and "star" model. I want to rate the restaurant using the model named "star" and do it in same template.But I'm having difficulties to do that. my review model kinda looks like this (Removed other attributes which aren't related to this problem): class Review(models.Model): review_title = models.CharField(verbose_name='Title', max_length=100) review_body = models.TextField() author = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) restaurant_or_techstore = models.CharField(verbose_name='Foods or Travel',max_length=20) slug = models.SlugField(null=False,unique=True,max_length = 300) My rating model looks like this: class Star(models.Model): post_id = models.ForeignKey(Review, on_delete = models.CASCADE ) food = models.FloatField(verbose_name='Food',null=False) service = models.FloatField(verbose_name='Food',null=False) cleanliness = models.FloatField(verbose_name='Food',null=False) and my view : def CreateReview(request): ImageFormSet = modelformset_factory(Image,form=ImageForm,extra=5) if request.method == 'POST': reviewForm = ReviewForm(request.POST) formset = ImageFormSet(request.POST,request.FILES,queryset=Image.objects.none()) starsForm = StarsrForm(request.POST) if reviewForm.is_valid() and formset.is_valid() and starsForm.is_valid(): review_form = reviewForm.save(commit=False) review_form.author = request.user review_form.post_or_discussion = 1 review_form.food_or_travel = 'Foods' review_form.save() reviewForm.save_m2m() starsForm.save() for form in formset.cleaned_data: if form: image = form['image'] photo = Image(review=review_form,image=image) photo.save() messages.success(request,'Image Uploaded Successfully') return HttpResponseRedirect("/") else: print(reviewForm.errors, formset.errors) else: reviewForm = ReviewForm() formset … -
Where the Http404 and PermissionDenied are handled exactly in django?
Where and how do the Http404 or PermissionDenied are handled exactly in django? I could not find functions or methods to catch these exceptions. -
ImportError: cannot import name 'ORDER_PATTERN' from 'django.db.models.sql.constants'
I want to add SearchFilter to the filte_backends but every time I imported rest_framework.filters I get this error