Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to merge the results of many QuerySets into a single QuerySet in Django?
I have a list of QuerySets (qs1, qs2, ..., qsn), whose length is not fixed (it varies depending on other variables). I need to merge all those QuerySets into a single QuerySet. I have something like this: list1 = [qs1, qs2, ..., qsn] I know there's a function in Django that allows me to do just this, but only if I know exactly how many QuerySets I want to join. Since in this case the number of QuerySets in the list (the ones that I want to merge) varies, I can't use qs1.union(qs2, qs3) because I won't always have just those three QuerySets in my list, sometimes I'll have just one or just two, or a thousand. Knowing that the length of the list is not fixed and that I need a final QuerySet that includes the results of all of the QuerySets within the list list1, no matter how many QuerySets it contains, is there a function that allows me to merge all the QuerySets inside this list into a single QuerySet? Thanks so much in advance. -
Sync a local firebird database with online Django database
So I have a sales software on my desktop based on firebird database so I want to build a website using Django syncing with the firebird database Is there any way to do it ? If there is show me the guidelines please it's really important for me Thanks I appreciate any help -
Error for start script when trying to deploy Django-React with Heroku
I am trying to deploy my first ever application, which has django for the backend and react for the frontend (with create-react-app). I followed the steps in some tutorials and managed to get my deploy build running but I am getting an error for npm start. I can't seem to find any solution, any help will be more than welcomed. 2021-06-11T21:48:08.784605+00:00 heroku[web.1]: State changed from crashed to starting 2021-06-11T21:48:22.000000+00:00 app[api]: Build succeeded 2021-06-11T21:48:25.830113+00:00 heroku[web.1]: Starting process with command `npm start` 2021-06-11T21:48:28.292792+00:00 app[web.1]: 2021-06-11T21:48:28.292815+00:00 app[web.1]: > ui@0.1.0 start /app 2021-06-11T21:48:28.292815+00:00 app[web.1]: > serve -s build 2021-06-11T21:48:28.292815+00:00 app[web.1]: 2021-06-11T21:48:28.297425+00:00 app[web.1]: sh: 1: serve: not found 2021-06-11T21:48:28.304774+00:00 app[web.1]: npm ERR! code ELIFECYCLE 2021-06-11T21:48:28.305084+00:00 app[web.1]: npm ERR! syscall spawn 2021-06-11T21:48:28.305267+00:00 app[web.1]: npm ERR! file sh 2021-06-11T21:48:28.305429+00:00 app[web.1]: npm ERR! errno ENOENT 2021-06-11T21:48:28.309100+00:00 app[web.1]: npm ERR! ui@0.1.0 start: `serve -s build` 2021-06-11T21:48:28.309179+00:00 app[web.1]: npm ERR! spawn ENOENT 2021-06-11T21:48:28.309293+00:00 app[web.1]: npm ERR! 2021-06-11T21:48:28.309384+00:00 app[web.1]: npm ERR! Failed at the ui@0.1.0 start script. 2021-06-11T21:48:28.309470+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above. 2021-06-11T21:48:28.315822+00:00 app[web.1]: 2021-06-11T21:48:28.316160+00:00 app[web.1]: npm ERR! A complete log of this run can be found in: 2021-06-11T21:48:28.316161+00:00 app[web.1]: npm ERR! /app/.npm/_logs/2021-06-11T21_48_28_310Z-debug.log 2021-06-11T21:48:28.376386+00:00 heroku[web.1]: Process exited … -
How can I shorten the full path to the file, to the name of the file in djano admin forms?
I have a standard Django admin form. When the file is uploaded in the file selection box, I would like to leave only the file name, instead of the full path in the static. Is this possible without editing the template, but only by overriding a formset, form, or model methods? In the picture above the button, change the display of the line "ws_document_studygroup/2021/2/123123123123123123png" to "123123123123123123png". But without changing the real path in the model. Please advise the best practice. -
How to handle API requests checking for the same key in Redis
I have been working with solution where I receive more than 100 requests for the same process at the same time (with a time diff of 1-2 milliseconds). In-order to process only one request and discard all, I have been setting a key common to all the requests in redis and check for this key in the second and other subsequent transactions, if found, should not progress further. What I observed is, since the transactions are coming in real time, by the time the first transaction sets the key, the second transaction executes as it dose not find the key in redis. What is the best way to solve this?. -
?Django - how do I select a different static file to use depending on user input in sessions?
Hopefully third time's a charm. I'm creating a Django website where users (who are learning Chinese) can upload Chinese vocabulary lists and the site will return a list of just the unique characters (no duplicates) that the user can download. So far, it's working and doing everything I described above. But the part that I'm stuck on is that I want to add a filter functionality. I want to add the option to exclude some of the more common Chinese characters from the list that the user downloads (what I'm thinking of as a filter feature). I have created a dropdown menu where before the user presses upload, they first say whether they want to filter out the 100 most common characters, 500, none, etc. Then, they move to another page where it should take that into account when it's writing to the file that it presents for the user to download. The logic of what I want to achieve would be something like: if the user selects one FilterPreference, then the web app should use the corresponding file in static files to filter out the characters in that file from the final output. I am fairly sure that I … -
How do I retrieve a user response token for reCAPTCHA in django?
I try to implement reCAPTCHA for my django website and I'm stuck at retrieving the users response token. Google docs says: Retrieve the user's response token from the web pages in one of following ways: The resolved value of the promise returned by the call to grecaptcha.enterprise.execute(). g-recaptcha-response POST parameter when a user submits the form on your site. As a string argument to your callback function if data-callback is specified in either the g-recaptcha HTML tag attribute or the callback parameter in the grecaptcha.enterprise.render method. truble is, that I don't know how to go about to do any of those three things. Can anyone give me a hint how to get that response token once someone submits the form and save it in a variable to use it in django? The form is something like this: <form id="contact-form" method="POST" action="{% url 'send_email' %}"> <a name="contact"></a> <label>Name</label> <input required class="input-field" type="text" name="name"> ... <label>Captcha:</label> <div class="g-recaptcha" data-sitekey="6Le..."></div> <input id="submit-btn" type="submit" value="Send"> </form> -
Check if value exists in firebase DB with Django
I have the following structure in my Firebase DB: { "users": { "-KKUmYgLYREWCnWeHCvO": { "fName": "Peter", "ID": "U1EL9SSUQ", "username": "peter01" }, "-KKUmYgLYREWCnWeHCvO": { "fName": "John", "ID": "U1EL5623", "username": "john.doe" } } } I want to check if ID with value U1EL5623 exists using Django. all_users = db.child('users').get(user['idToken']) for user in all_users.each(): if user.ID == "U1EL9SSUQ": print(user.username) And i have this error 'Pyre' object has no attribute 'ID' Regards./ -
Django rest framework value from data variable
I'm trying to create API that will get post request with the ('command', 'name', 'APIToken') variables. After that I need that the API will execute local python script with those variables but I can't find a way to extract those values from the request. Any suggestions ? -
Django self.request.POST.get() returning None
I am trying to create a search button for my database. But my self.request.POST.get('searched') is returning None the form: <form class="d-flex" action="{% url 'asset_app_search' %}">{% csrf_token %} <input class="form-control me-2" type="search" placeholder="Søg" aria-label="Search" name="searched"> <button class="btn btn-outline-secondary" type="submit">Søg</button> - </form> my views.py class SearchView(generic.TemplateView): template_name = "asset_app/search.html" def post(self): searched = self.request.POST.get('searched') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) searched = self.post() context['searched'] = searched context_entry_today = datetime.date.today() context_entry_overdue = datetime.date.today() - datetime.timedelta(days=90) context_entry_inspection_time = datetime.date.today() - datetime.timedelta(days=76) context['assets'] = models.Asset.objects.order_by('name') context['rooms'] = models.Room.objects.order_by('last_inspected', 'location', 'name') context['bundelReservations'] = models.Bundle_reservation.objects.order_by('return_date') context['loan_assets'] = models.Loan_asset.objects.order_by('return_date') context['to_dos'] = to_do_list_app.models.Jobs.objects.all() context['today'] = context_entry_today context['overdue'] = context_entry_overdue context['inspection_time'] = context_entry_inspection_time return context and what is beeing posted [11/Jun/2021 22:55:23] "GET /asset/search/?csrfmiddlewaretoken=fqb8jppygSbZ10ET8AXw6dd5B77z5OYudNJU0uyjp8jFNYDG57nkNvrcx5lHFsPo&searched=sdfdsff HTTP/1.1" 200 10418 -
How do I use another website's login system to authenticate my users?
I am trying to build an app with Django and React, and I would like to use this login flow: User goes to my app's login page Once they are on my app's login page, they click a button that redirects them to another website's login page Important note: I do NOT want to use Google, Facebook, or any other social provider for this authentication. I want to use a specific website Once the user has logged in on that website, they are redirected to the pages on my website that require authentication I have looked into SSO and its various solutions to solve my problem, but it is a bit convoluted - does anyone have any advice to send me down the correct, general direction? -
Django Rest Framework serializer check if exists in related Many to Many fiield
I have a custom User model with a blocked field as class User(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] blocked = models.ManyToManyField("User", related_name="blocked_by", blank=True) and I'm trying to have a serializer where I can look up a user by their ID and find out if they are blocked or not by the logged in user my current is serializer class UserSerializer(serializers.ModelSerializer): is_blocked = serializers.BooleanField() # need to populate this class Meta: model = User fields = ['id', 'email', 'user_type', 'is_blocked'] and my view class UserDetail(generics.RetrieveAPIView): authentication_classes = (authentication.JWTAuthentication,) permission_classes = (permissions.IsAuthenticated,) serializer_class = UserSerializer queryset = User.objects.all() I'm just not sure how to populate that value such that it'd be true if the inquiried user is in the blocked manyToMany field of the logged in user or not -
Django/DRF backend not receiving complete data from POST request
I'm trying to send data to my Django/DRF backend via Axios POST requests. Some of them have been working, but some of them haven't been. This snippet, for example, works fine: axiosInstance.post( `/api/notes/`, { title, content: serialize(editorContent), } ) This one, however, has been causing problems: axiosInstance.post( `/api/notebooks/`, { name: newNotebookName, user, } ) In the second snippet, the name attribute gets through to the backend, but for some reason the user attribute does not. I tried using console.log to see if user is undefined at the moment it's sent off to the backend and it isn't. I tried to change the way I define the keys in the object I send to the backend so that they're not dynamic like in this answer and the result hasn't changed. The user variable is a string containing an email address, like 'foobar@gmail.com'. I thought maybe Django blocked it by default for security reasons, but I split the string at the @ and tried sending the first part only and it didn't work either. I also tried defining a new variable so that the type of user is string rather than string | undefined and it still doesn't work. The value of … -
A complex Django QuerySet query using ForeignKey
I'm using Django. I created 3 models: Category, Feature, Question. class Category(models.Model): category_name = models.CharField(max_length=300) category_order = IntegerRangeField(default=0, min_value=0) category_visible = models.BooleanField(default=True) def __str__(self): return self.category_name class Meta(object): ordering = ['category_order'] class Feature(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) feature_name = models.CharField(max_length=300) feature_code = models.CharField(max_length=50, unique=True) feature_predictable = models.BooleanField(default=False) def __str__(self): return self.feature_name class Question(models.Model): feature = models.ForeignKey(Feature, on_delete=models.CASCADE, unique=True) question_order = IntegerRangeField(default=0, min_value=0) question_text = models.CharField(max_length=300) question_visible = models.BooleanField(default=True) def __str__(self): return self.question_text class Meta(object): ordering = ['question_order'] I want to write a function that will return me a list of categories with category_visible == True and the value of feature_predictable for at least one instance of the Feature model in that category is True, and for at least one Question question_visible == True. Currently, I managed to create something like this: category_queryset = category_queryset.filter(category_visible=True) category_ids = [] for category in category_queryset: for feature in category.feature_set.all(): if feature.feature_predictable is not True: continue for question in feature.question_set.all(): if question.question_visible is not True: continue if category.id not in category_ids: category_ids.append(category.id) return Category.objects.all().filter(id__in=category_ids) But this is probably not the most efficient way. How to write it better? Thank you in advance for your help. -
Remove focus ring & border from Django forms using TailwindCSS
Goal: No border or focus ring in Django form. Current: I can currently only change certain attributes like text color & rounded corners but not border or focus. I am using django-widget-tweaks to assign class attributes to the form. I am using django-tailwindcss to use tailwind in Django. Attempted: I am using the tailwind ring-0 & border-0 tailwind attributes but they are not functioning at all. Code: {% load widget_tweaks %} <form action="{% url 'marketing:subscribe' %}" method="post"> {% csrf_token %} {{ form.email|add_class:"bg-black rounded-lg border-0 ring-0 focus:ring-0" }} <button class="text-green-300" type="submit">Subscribe</button> </form> -
Django Crispy Forms not working as fully intended
currently learning how to use Django and following Corey Shafer's videos to learn. So far I am able to follow along pretty easily but I am running into a formatting error when trying to use crispy forms. Right now when using it, it works to an extent but not fully. Here is what I am currently getting Here is what is expected from the videos As you can see, some of it works as intended with proper feedback and the descriptions formatted a little more clearer. But as you can see the text isn't formatted to be smaller and the feedback text isn't red but just bolded. I included below what I added to html template to implement crispy. Also for my settings.py I made sure to add CRSIPY_TEMPLATE_PACK = 'bootstrap4' and included it under my INSTALLED APPS list. This is my first time posting so if there is any information I am missing please let me know, thank you for your time! {% extends "blog/base.html" %} {% load crispy_forms_tags %} {% block content%} <div class = "content-selection"> <form method = "POST"> {% csrf_token %} <fieldset class = "form-group"> <legend class = "border-bottom mb-4">Join Today</legend> {{ form|crispy }} </fieldset> <div … -
Why can't I use third party database in Heroku? (If can, how?)
I am using Django+React stack and trying to use Mongo Atlas, but I can't use it because Heroku uses Postgresql by default as a free add-on. To fix this I detached the Postgres database and re-deployed the application But now it says, can't connect to the database And this is certainly the case with every other database like MySQL Please guide me "How can I use any other database in Heroku", BUT WITHOUT PAYING FOR ADD-ONS. (I mean, of course, I am using Atlas just so that I don't have to pay for the MongoDB add-on in Heroku) If there is no answer existing to this question, please at least tell me any service where I can deploy my Django application with the MongoDB database. (PS: I am a student that's why I can't pay :|) -
Retrieve particular field from my database
I would like to print the dates stored in my models.py. However, it seems like Django couldn't access them. Here you can have a look at the relevant pieces of my code: views.py from django.db.models.fields import DateTimeField from django.http.response import HttpResponseRedirect from django.shortcuts import render from django.urls import reverse from django.utils import timezone from datetime import datetime from .models import Aufgabenzettel # Create your views here. def index(request): now = datetime.now() Aufgaben_items = Aufgabenzettel.objects.all().order_by("-Geplant") #arrange objects in the correct order for Aufgabenzettel.Geplant in Aufgaben_items: #run through the loop and... print(Aufgabenzettel.Geplant) if Aufgabenzettel.Geplant == now: #...search for items in the database where the scheduled time ("Geplant") is equal to the current time return render (request, "aufgabenzettel/add.html") #response in any way e.g. by returning the add.html return render(request, "aufgabenzettel/index.html", { "Aufgabenliste":Aufgabenzettel.objects.all(), #currently not used "Aufgaben_items":Aufgaben_items }) models.py from django.db import models # Create your models here. class Aufgabenzettel(models.Model): Aufgabeselbst = models.CharField(max_length=64) Datum = models.DateTimeField(auto_now_add=True) Geplant = models.DateTimeField(auto_now_add=False, auto_now=False) def __str__(self): return f"{self.Aufgabeselbst}" Whenever I execute the index function it prints the data stored as CharField in Aufgabenzettel.Aufgabeselbst. If I change it to print(Aufgabenzettel.Datum) it prints as result <django.db.models.query_utils.DeferredAttribute object at 0x00000203BAD2A7C0>. My goal is to compare if Aufgabenzettel.Geplant == now and get … -
Django 'ListBlogPost' object has no attribute 'get_object'
here is my code. I am new in django. I am not understanding why I am getting this error 'ListBlogPost' object has no attribute 'get_object. anyone please help: #views.py class ListBlogPost(ListView,FormView): model = Blog template_name = 'blog.html' form_class = BlogFrom def get_success_url(self): return reverse('blog') def get_context_data(self, **kwargs): data = super(ListBlogPost, self).get_context_data(**kwargs) data['blog_admin_form'] = BlogFrom() return data def post(self, request, *args, **kwargs): self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): form.save() return super(ListBlogPost, self).form_valid(form) -
Django not logging and redirecting user
Please do not downvote, I know this question is probably easy to answer I just can't figure this out. I am creating a simple register and login system for my Django web application. I am able to successfully create a user and save it to the Django database, but I am struggling with logging a user in. I want to log a user in and redirect them to the dashboard.html page, but it won't work. All of my code is down bellow. Thank you to everyone who helps! Views.py def index(request,*args, **kwargs): return render(request, "index.html", {} ) def dashboard(request,*args, **kwargs): return render(request, "dashboard.html", {} ) def register(request, ): form = CreateUserForm() if request.method == "POST": form = CreateUserForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'Your account has been successfully created, {username} ') return redirect('loginpage') context = {'form': form} return render(request, "register.html", context ) def loginpage(request): if request.method == "POST": username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username =username, password = password) if user is not None: login(request, user) return redirect('dashboard') context = {} return render(request,"login.html") Urls.py urlpatterns = [ path('',views.index, name = 'index'), path('home/',views.index, name = 'index'), path('register/',views.register, name = 'register'), path('admin/', admin.site.urls), path('login/', views.loginpage, name = … -
Translating words in array in javascript file in django
I installed the JavaScript Catalog for translating text in javascript files as explained in the docs: https://docs.djangoproject.com/en/3.2/topics/i18n/translation/#module-django.views.i18n That works well. I can create the PO translation files and als make and compile the translations. For example: gettext("my-translation") will work just fine. Now I want get an array from an API call which looks like this: let arr = ["red", "green", "yellow", "blue"]. I don't know how I can use gettext to create the translations for each word in the array. I tried to map it with arr.map(i => gettext( + i + ")"));. I also tried to add it to the whole array with gettext(arr), but no success. My websearches did not help me. I cannot change the representation of the array, so I need to do this in the frontend. Is there any trick for this? Thanks for any help and hints. -
How to enable a user to add something to a site on Django
I am trying to enable the user to add new hotel on site when he is logged in. I have made registration, login and also I can add something when user is logged in, but it is not added by logged user, it is added by superuser and that is what I want to do. There is my codes and I hope you will help me. views.py (accounts) def register(request): if request.method == 'POST': first_name = request.POST['first_name'] last_name = request.POST['last_name'] username = request.POST['username'] email = request.POST['email'] password1 = request.POST['password1'] password2 = request.POST['password2'] if password1 == password2: if User.objects.filter(username=username).exists(): messages.warning(request,"username taken") return render(request, 'register.html') elif User.objects.filter(email=email).exists(): messages.warning(request,"email taken") return render(request, 'register.html') else: user = User.objects.create_user(username=username, password=password1, email=email, first_name=first_name, last_name=last_name) user.save() messages.success(request,"Account successfully created, thank you for register.") createduser = True return render(request, 'register.html') else: messages.warning(request,"Password does not match, please, try again.") return render(request, 'register.html') else: print('Account has not created, please, try again.') return render(request, 'register.html') models.py from django.db import models class Hotel(models.Model): name = models.CharField(max_length=50) short_description = models.TextField(max_length=250) long_description = models.TextField(max_length=2000, null=True) HOTEL_STARS = ( ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5') ) stars = models.TextField(max_length=1, default=5, choices=HOTEL_STARS, null=True) pictures = models.ImageField(upload_to="images", default="images/default.jpg") created = models.DateTimeField(auto_now_add=True, null=True) def … -
Form not submitting unless submitting twice. Ajax, vanilla js, django
I am trying to submit a Django form with AJAX and Vanilla JavaScript however the form is not actually submitting unless I click the submit button twice. I have an event listener on the form that stops the default submission to avoid page reload and then I open a XMLHttpRequest. On the first submission I get a 200 response but the data hasn't actually been sent to the database. However if I click the submit button again I get the desired 201 (item created) response from the server and it reloads my posts and adds the new one perfectly. I am still a bit unfamiliar on working with asynchronous data and cannot figure out why it's not working. If I remove the e.preventDefault the form submits correctly and the new post shows up after the page reloads. relevant JS snippet: const postCreateFormEl = document.getElementById("post-create-form") const postsEl = document.getElementById("posts") const handlePostSubmit = function(e){ e.preventDefault() const myForm = e.target const myFormData = new FormData(myForm) const url = myForm.getAttribute("action") const method = myForm.getAttribute("method") const xhr = new XMLHttpRequest() xhr.open(method, url) xhr.setRequestHeader("HTTP_X_REQUESTED_WITH", "XMLHttpRequest") xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest") xhr.onload = function() { const serverResponse = xhr.response console.log(serverResponse, xhr.status) const postsEl = document.getElementById("posts") loadPosts(postsEl) } xhr.send(myFormData) } postCreateFormEl.addEventListener("submit", … -
Write a title that summarizes the specific problem(ERROR HOSTING DJANGO WEBSITE)
Hey everyone i m new to django , and trying to deploy django website on heroku but showing some errors plz help. ERROR:- import numpy ModuleNotFoundError: No module named 'numpy' ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. ! Push rejected, failed to compile Python app. ! Push failed here is my files:- https://github.com/Taranjeet105/TextAnalyzer Thank in advance -
Django Form validation Pseudo Code algorithm
I have always struggled with form validation in Django, I made some pseudo code to reference while reading through all the documentation, is my understanding of how validation works correct, any corrections or improvements to the below pseudo code? form.is_valid() or form.errors: # form.is_valid() is perferred way form.full_clean() = for field in form.fields: field_name = field.field_name field.clean() = try: form.cleaned_data[field_name] = field.to_python() = # Accepts raw value from widget and coerces it. E.g. A FloatField will turn the data into a Python float or raise a Validation Error. return cleaned_value := (coerce)value field.validate() = # *Override this # For custom field-specific validation that is not suitable for a validator (which tend to be generic). # Should not alter the value. if not custom_validation(): raise ValidationError() return # Does not return anything field.run_validators() = # Should not need to override this errors = [] try: for validator in field.validators: validator.validate() except ValidationError as e: errors += e form.cleaned_data[field_name] = form.clean_<field_name> = # *Override this # Custom field cleaning. # Must return a value, as it replaces the value in cleaned_data. cleaned_value = self.cleaned_data[field_name] custom_cleaned_value = custom_clean(cleaned_value) return custom_cleaned_value except ValidationError: continue form.clean() # *Override this # Place custom validation that depends …