Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django validate queryset None
I have a queryset in order to check if the result is Null or exists cupon_existente = Orden.objects.filter(user = self.request.user, ordenado= False).values_list('promo', flat=True) when the result is 'None' and I want to validate like this: if cupon_existente: True else: False it validates as 'True' how can I validate that None is actually 'False' or 'NULL' ? -
How to implement a login page using Django Channels
I ma trying to make a server using Django and Channels and I want to make a login page. After some googling I have found answers on how to implement the backend, but what I want to know is: What should I do when it comes to the frontend and how can I link this to the backend? -
DJango GET Request from database into JSON
I got a question with my Django project. I have a database and want to get data into JavaScript with a fetch request. The data should just be in JSON. This was my attempt with Serializer. Is there a more easy way, than writing a whole serializer.py. Does anybody have an idea what to do. JavaScript: fetch('', { method: 'GET', }) .then(response => response.json()) .then(data => { console.log(data); }); DJango views.py: def ausgeben(request): if request.method == 'GET': ausgeben = Schraube.objects.all() serializer = SchraubeSerializer(schrauben, many=True) return JsonResponse(serializer.data, safe=False) return render(request, 'AR-Ausgeben.html', all_items) -
Django Summernote clean() got an unexpected keyword argument 'styles' in DjangoForms
I have a Django app hosted on Heroku. I have Summernotes installed on the Django forms, however, when I submit the forms I get the error: clean() got an unexpected keyword argument 'styles' Exception Location: /app/.heroku/python/lib/python3.10/site-packages/django_summernote/fields.py, line 18, in to_python I can edit this file on the local host and remove styles=STYLES and it will work on localhost but I am unable to edit this on Heroku. This error also shows up if i try and edit via the admin. I'm lost on what to try next. Thank you in advance. from django.db import models from django.forms import fields import bleach from django_summernote.settings import ALLOWED_TAGS, ATTRIBUTES, STYLES from django_summernote.widgets import SummernoteWidget # code based on https://github.com/shaunsephton/django-ckeditor class SummernoteTextFormField(fields.CharField): def __init__(self, *args, **kwargs): kwargs.update({'widget': SummernoteWidget()}) super().__init__(*args, **kwargs) def to_python(self, value): value = super().to_python(value) return bleach.clean( value, tags=ALLOWED_TAGS, attributes=ATTRIBUTES, styles=STYLES) class SummernoteTextField(models.TextField): def formfield(self, **kwargs): kwargs.update({'form_class': SummernoteTextFormField}) return super().formfield(**kwargs) def to_python(self, value): value = super().to_python(value) return bleach.clean( value, tags=ALLOWED_TAGS, attributes=ATTRIBUTES, styles=STYLES) I do have this in the settings files but it doesn't do anything: STYLES = [ 'background-color', 'font-size', 'line-height', 'color', 'font-family' ] My models.py from django.db.models.signals import post_save, post_delete from django.db import models from model_utils import Choices from django.contrib.auth.models import User … -
Add multiple products in session [Django]
I would like to add several products to build my basket, but each time I add another product it overwrites the first one, how do I add several products in session? Views.py def cart_add(request, code): dico={"produits":[{'code':'MLO31','nom':'banane sucré','prix':1500}, {'code':'BRAD5','nom':'pomme de terre','prix':1800}]} mes_produits=dico['produits'] session=request.session selected_product = next((item for item in mes_produits if item["code"] == code), None) if selected_product != None: session['nom']=selected_product.get('nom') session['prix']=selected_product.get('prix') contex={'nom':session['nom'],'prix':session['prix']} return render(request, 'cart/cart_detail.html',contex) cart_detail.html {% for key,value in request.session.items %} Nom : {{request.session.nom}} Prix : {{request.session.prix}}<br> {% endfor %} -
How do I filter on related objects that's fetched by prefetch_related without executing additional SQL queries?
The below snippet is from Django doc: https://docs.djangoproject.com/en/4.1/ref/models/querysets/ >>> pizzas = Pizza.objects.prefetch_related('toppings') >>> [list(pizza.toppings.filter(spicy=True)) for pizza in pizzas] The second line executes additional SQL queries. Is there a Django native way of writing the above that filters in memory instead of executing SQL against db? alternatively I can just write this without generating more SQL queries: [[topping for topping in pizza.toppings if topping.spicy == True] for pizza in pizzas] -
HackerNews API extraction error - TypeError: list indices must be integers or slices, not str
Trying to run this code to get the topstories from hacker news is giving me this error 'TypeError: list indices must be integers or slices, not str', the error is generated at story = data['story'] from multiprocessing import context from django.shortcuts import render import requests # Create your views here. def index(request): #make an api call and save response url = f'https://hacker-news.firebaseio.com/v0/topstories.json' response = requests.get(url) data = response.json() story = data['story'] context = { 'story': story } return render(request, 'SyncNews/index.html', context) What can I do to correct this error as I'm following a video showing a similar project but this error was not seen, I've also tried removing the '' but receive an error 'UnboundLocalError at / local variable 'story' referenced before assignment' story = data['story'] -
Gmail SMTP Connection "unexpectedly closed" after sending some mails w/ multithreading
I'm trying to use a multithreading approach to speed up sending multiple individual emails using the Django framework and the Gmail SMTP, but I'm running into issues with my connection being dropped It is important to know that I can manage to send about 50 or 55 emails untill my connection is dropped with this error: smtplib.SMTPServerDisconnected: Connection unexpectedly closed I can't use Django send_mass_email method because I need to be able to register if each mail is sent or failed in a database for auditing purposes My code looks like this: class Threading(Thread): def __init__(self, emails): self.emails = emails Threading.thread(self) def thread(self): queue = Queue() #4 worker threads for x in range(4): worker = SenderWorker(queue) worker.daemon = True worker.start() for email in self.emails: queue.put( email ) queue.join() And the SenderWorker class: class SenderWorker(Thread): def __init__(self, queue): Thread.__init__(self) self.queue = queue def run(self): start = datetime.now() while True: email = self.queue.get() try: Email.sendEmail( email ) #method for sending and logging a single email sent finally: self.queue.task_done() My SMTP config looks like this: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'anon@anonymous.com' SERVER_EMAIL = 'anon@anonymous.com' EMAIL_HOST_PASSWORD = '*******' DEFAULT_FROM_EMAIL = EMAIL_HOST_USER I've tried so far: … -
How to generate html test report in selenium while triggering my test with Django and Plain html as my test script is running but generating nothing?
This is my viws.py file # Create your views here. def test_home(request): return render(request, 'Acode.html') def end_home(request): return render(request, 'After.html') @csrf_exempt def run_home(request): if request.method == 'POST': objs = json.loads(request.body) for val in objs: if val=='1.1': l= login() l.setUpClass() l.test_menu() l.tearDownClass() if val=='1.2': l= create_course_test() l.setUpClass() l.test_admin_Page() l.tearDownClass() if val=='1.3': l= create_course_test_draft() l.setUpClass() l.test_admin_Page() l.tearDownClass() content = '<p>dummy content</p>' return HttpResponse(content) // Test.Login_Menu_Test file: @classmethod def setUpClass(cls): const = 'https://trainingroot.z29.web.core.windows.net/' cls.driver.get(const) cls.driver.maximize_window() def test_menu(self): self.const = 'https://trainingroot.z29.web.core.windows.net/' currentList = self.driver.find_elements(By.TAG_NAME, 'a').sort() previousList = Project_urls.urls.sort() WebDriverWait(self.driver, 10).until( EC.presence_of_element_located( (By.XPATH, '//*[@id="single-spa-application:@Training"]/div/div/div[1]/p'))) if currentList == previousList: self.driver.get(self.const + 'home') self.driver.get(self.const + 'course category') self.driver.get(self.const + 'calender') self.driver.get(self.const + 'FAQ') self.driver.get(self.const + 'expert') self.driver.get(self.const + 'requesttraining') self.driver.get(self.const + 'myachievements') else: print('Some thing is missing') @classmethod def tearDownClass(cls): cls.driver.close() cls.driver.quit() print('Test Completed') if name == 'main': unittest.main(testRunner=HtmlTestRunner.HTMLTestRunner(output='../Selenium/Reports')) // my code is generating test reports only when I trigger it from the terminal but I want to trigger it with the Django application... // If I put the last statement inside the teardown function, then it doesn't start and may be the root cause of the problem -
Lack of Log Entry for Unhandled Error in Server Side SuiteScript 2.x
I suppose that this is more of a curiosity as opposed to an actual issue, but I thought I'd ask about it anyway. There are times when an uncaught error occurs in a server-side NetSuite script using SuiteScript 2.0/2.1 (2.x), but instead of seeing a "SYSTEM" scripting log entry, there's nothing. It gives the appearance of a script just stopping for no reason. Now, I know this can easily be avoided by wrapping everything within a try-catch block, but that's not what I'm trying to discuss here. Does anyone have any insight into why a script would just stop without any SYSTEM error logging? It's just something I find interesting given that with the 1.0 API uncaught errors would always get logged. And it's not a guarantee that an uncaught error won't be logged as a SYSTEM log. It seems more common with map/reduce scripts, but unless memory is not serving correctly I believe that I have seen it happen with suitelets and user event scripts, too. Just thought that I'd pose the question here to see if there was anyone who might know a little something about it. -
How can i make my input in my templates save in same template page and in database using django. Please help i am new here
I created a model. i want my input data from my template page to show on that same page after clicking submit and that same data should save in my database in the model -
What are Django swappable models?
What are swappable models in Django? And Why sometimes when we do a migration a swappable dependency appears in Django migration files? I have searched for this concept in Django but I did not understand what it really does?! -
How to limit form submit request in Django app
I want to limit submitting request for visitors(anonymous) in my django app. Suppose 10 or 50 limits per day/month. If they try to search more than my given limit I want to show a message "you have reached your daily or monthly limit!" How can I do this? Here is views: def homeview(request): if request.method == "POST" and 'text1' in request.POST: text1 = request.POST.get('text1') text2 = request.POST.get('text2') data = my_custom_function(text1, text2) context = {'data': data} else: context = {} return render(request, 'home.html', context) here is form in template: <form action="" method="POST"> {% csrf_token %} <input class="form-control m-3 w-50 mx-auto" type="text" name="text1" id="text1" placeholder=""> <input class="form-control m-3 w-50 mx-auto" type="text" name="text2" id="text2" placeholder=""> <input class="btn btn-primary btn-lg my-3" type="submit" value="Submit"> </form> -
Upgrading Django 3.1.7 to 4.0.7 along with python 3.10 facing issues in project
Below are the error when try to run the project using django 4.0.7. If I downgrade django to 3.1.7 everything work fine. Exception in thread django-main-thread: Traceback (most recent call last): File "/usr/lib/python3.10/threading.py", line 1009, in _bootstrap_inner self.run() File "/usr/lib/python3.10/threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/lib/python3.10/site-packages/django/core/management/commands/runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "/lib/python3.10/site-packages/django/utils/autoreload.py", line 87, in raise_last_exception raise _exception[1] File "/lib/python3.10/site-packages/django/core/management/init.py", line 398, in execute autoreload.check_errors(django.setup)() File "/lib/python3.10/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/lib/python3.10/site-packages/django/init.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/lib/python3.10/site-packages/django/apps/config.py", line 126, in create mod = import_module(mod_path) File "/usr/lib/python3.10/importlib/init.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1006, in _find_and_load_unlocked File "", line 688, in _load_unlocked File "", line 883, in exec_module File "", line 241, in _call_with_frames_removed File "/rest_registration/apps.py", line 3, in import rest_registration.checks # noqa File "/rest_registration/checks.py", line 33, in def auth_installed_check(): File "/lib/python3.10/site-packages/django/core/checks/registry.py", line 52, in inner raise TypeError( TypeError: Check functions must accept key arguments (**kwargs). -
i am trying to visit the admin link in my django server link, but i keep getting a, "TypeError at /admin". i did notice the "venv" folder gives a sign
#admin.py from django.contrib import admin Register your models here. from .models import Student admin.site.register(Student) #models.py class Student(models.Model): id = models.CharField(max_length=50) surname = models.CharField(max_length=50) first_name = models.CharField(max_length=50) gender = models.CharField(max_length=6) course = models.TextField() -
Facet Filter List using django-filter
I'm trying to build a facet Filter using django-filter. Also in filter, I have Postgres full-text search. Filter and search work good, but I don't know how to build a facet Filter. For example, I want that when I select Chinese, then I see count each value and related value in filter. Could you please give me any advice how to build it? models.py class Book(models.Model): name = models.CharField(max_length=255) author = models.ForeignKey( "Authors", on_delete=models.SET_NULL, null=True, blank=True, ) subject = TreeManyToManyField("Subject") published_date = models.DateField(blank=True, null=True) language = models.ForeignKey( "Language", on_delete=models.SET_NULL, null=True) class Subject(MPTTModel): name = models.CharField( max_length=1000, unique=True, ) class Language(models.Model): name = models.CharField( max_length=255, unique=True, ) class Authors(models.Model): name = models.CharField( max_length=255, unique=True, ) filters.py class BookFilter(django_filters.FilterSet): search = django_filters.CharFilter( method="my_custom_filter", widget=TextInput( attrs={ "class": "form-control", "placeholder": _("Type to search"), } ), ) language = django_filters.ModelMultipleChoiceFilter( field_name="language", queryset=Language.objects.order_by("name"), widget=forms.CheckboxSelectMultiple(), ) subject = django_filters.ModelMultipleChoiceFilter( field_name="subject", queryset=Subject.objects.all(), widget=autocomplete.ModelSelect2Multiple(} ), ) class Meta: model = Book fields = { "subject", "language", "published_date", } def my_custom_filter(self, queryset, name, value): q = value return ( queryset.annotate( rank=SearchRank(vector, q), similarity=TrigramSimilarity("title", q) + similarity=TrigramSimilarity("author", q) ) views.py def BookListView(request): book = Book.objects.all() filter = BookFilter(request.GET, queryset=book) context = { "filter": filter, "book": book, } return render(request, "book.html", context) … -
Can`t run `manage.py test` in Django: django.db.utils.OperationalError
I`m trying to run some auto-tests in Django framework 4.0.4 by command python manage.py test test.to.run Also at the start it gets notification: RuntimeWarning: Normally Django will use a connection to the 'postgres' database to avoid running initialization queries against the production database when it's not needed (for example, when running tests). Django was unable to create a connection to the 'postgres' database and will use the first PostgreSQL database instead. , but at the result it gets error without any specific explanation: ...conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError The above exception was the direct cause of the following exception: ... conn = _connect(dsn, connection_factory=connection_factory, **kwasync) django.db.utils.OperationalError Connected DB is postgres located on another computer in the local network. When I run app on dev-server by command python manage.py runserver everything goes ok, there are no troubles with database. I tried to create local postgres database on my machine and set connection to it in settings.py, python manage.py test runs as well too. -
how do I edit the user detail/profile of other users?
This to be done through user defined admin page and not the Django admin page. I would like to access and edit the user details of other users that have registered to my site. I already have a self edit function in my views but would like to add more accessibility to the admin role in case of user emergency. This is my self edit views code. What should be the value to insert into instance field (I assume) to get the details of the user the admin selects. if request.method == "POST": form = NewEditForm(request.POST, instance=request.user) Sform = StudentForm(request.POST, instance=request.user) if form.is_valid() and Sform.is_valid(): user = form.save() student = Sform.save(commit=False) student.user = user student.save() messages.success(request, ("Profile updated.")) return HttpResponseRedirect("/clubhomepage") messages.error(request, "Unsuccessful update. Invalid information.") else: form = NewEditForm(instance=request.user) Sform = StudentForm(instance=request.user) return render(request=request, template_name="App2/edituser.html", context={"edit_form": form, "Student": Sform }) I am still kinda new to django so any help would be appreciated. -
"ModelForm has no model class specified."
I am trying to create a Register Form but I couldn't find any solution "ModelForm has no model class specified." for this error. I didn't use ModelForm but I take this error. Can somebody explain me why am I taking this error and how can I fix it // views.py// from django.shortcuts import render from .forms import RegisterForm from django.contrib import messages from django.contrib.auth import login as dj_login def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): user = { "username": form.cleaned_data["username"], "email": form.cleaned_data["email"], "phone": form.cleaned_data["phone"], "password1": form.cleaned_data["password1"], "password2": form.cleaned_data["password2"] } user = form.save() dj_login(request,user) messages.success(request,"You have completed registration successfully.") return render(request,"index.html",{"user":user}) else: messages.info(request,"You couldn't complete registrations!") else: form = RegisterForm() return render(request,"register.html",{"form":form}) // forms.py // from django import forms from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User class RegisterForm(UserCreationForm): email = forms.EmailField(required=True) phone = forms.IntegerField(required=True) class Meta(): user = User fields = ["username","email","phone","password1","password2"] def save(self, commit=True): user = super(RegisterForm, self).save(commit=False) user.email = self.cleaned_data["email"] user.phone = self.cleaned_data["phone"] if commit: user.save() return user -
How to test Django custom decorator with different values?
I've got a function based view like this: @new_group_required("special_group", raise_exception=True) def my_view(request): <my code> I'd like to test this as if the raise_exception was set to False but I can't seem to figure out through google how to do this. Some people recommend using Mock but I'm pretty unfamiliar with Mock and how I can run my_view, but change just the attribute of that decorator. Any help would be appreciated! The decorator code looks like this (very similar to the built-in Permission decorator from Django): def user_passes_test( test_func, login_url=None, redirect_field_name=REDIRECT_FIELD_NAME ): """ Decorator for views that checks that the user passes the given test, redirecting to the log-in page if necessary. The test should be a callable that takes the user object and returns True if the user passes. """ def decorator(view_func): @wraps(view_func) def _wrapper_view(request, *args, **kwargs): if test_func(request.user): return view_func(request, *args, **kwargs) path = request.build_absolute_uri() resolved_login_url = resolve_url(login_url or settings.LOGIN_URL) # If the login url is the same scheme and net location then just # use the path as the "next" url. login_scheme, login_netloc = urlparse(resolved_login_url)[:2] current_scheme, current_netloc = urlparse(path)[:2] if (not login_scheme or login_scheme == current_scheme) and ( not login_netloc or login_netloc == current_netloc ): path = request.get_full_path() … -
Can't see images after deploying to heroku
I had uploaded my site Django app on Heroku server when I upload image file in my admin panel is successfully uploaded but i can't see it in my page settings.py STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = 'static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', "whitenoise.middleware.WhiteNoiseMiddleware", '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', ] urls.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) template {% for data in datas %} <li class="nav-item dropdown pe-3"> <a class="nav-link nav-profile d-flex align-items-center pe-0" href="#" data-bs-toggle="dropdown"> <img src= {{data.profile_image}} alt="Profile" class="rounded-circle"> <span class="d-none d-md-block dropdown-toggle ps-2">{{user.username}}</span> -
How to order a queryset based on the multiselectfield values
choix = ( ('Proche station ski','Proche station ski'), ('Piscine', 'Piscine'), ('Jardin', 'Jardin'), ('Cave', 'Cave'), ('Parking', 'Parking'), ) class Appartement(models.Model): surface = models.FloatField() prix = modelsenter code here.FloatField() nombre_piece = models.IntegerField() list_caracteristiques = MultiSelectField(choices=choix, max_length = 200) program = models.ForeignKey(Programme_immobilier, on_delete=models.CASCADE) def __str__(self) -> str: return f"Appartement {self.id} de {self.program_id}" My task is to do the following: List the apartments by ordering the answer according to the season (according to the date of the request) as follows: o In winter (December – March) the apartments that are "Proche station ski" appear first, then sort by decreasing price, decreasing area, o In summer (June – September) the apartments with a "Piscine" appear first, then sort by decreasing price, decreasing area. Otherwise, sorting is by decreasing price, decreasing area I am stuck at how to sort the queryset, based on the values of the multiselectfield Thanks in advance for any cooperation ! -
Add loading view during process of the next view in Django
I want to add a loading page during the process, I tried all the solutions here in stackoverflow and different articales, but I'm really surprised that the solutions did not work for me, It's been 2 days and I still didn't find a solution. I have two pages Home and datatable I want to add a loading page when i redirect from the home page to the datatable one. Please any help is highly appreciated. this is my view.py : def home_view(request): context = {} context ['form'] = Scraping() return render(request,'home.html', context) def datatable_view(request): if request.method =='POST': if form.is_valid(): return render(request,'datatable.html') -
Django + HTMX - create/update parent model with child models at once
I found a great tutorial about dynamically saving models in django using HTMX: Video: https://www.youtube.com/watch?v=KVq_DjIfnBo Text version: https://justdjango.com/blog/dynamic-forms-in-django-htmx My problem is that I want to create author, add books and save author with books at once - using HTMX on one page. Could you please explain, how to do it? Thank you -
How to disallow to change "status" for simple user and keep it for admin and support(superuser)?
The simple user must either not see the status button or it must be grayed out for selection. Admin(user.is_staff) and Support(user.is_superuser) should see the field and be able to change it. Now user can change the status of ticket in Update view. My serializer: class TicketSerializerUpdate(serializers.ModelSerializer): user = serializers.HiddenField(default=serializers.CurrentUserDefault()) status = Status.objects.all() class Meta: model = Ticket fields = "__all__" My models Ticket and Status: class Status(models.Model): status = models.CharField(max_length=150) desc_status = models.TextField() def __str__(self): return self.status class Ticket(models.Model): title = models.CharField(max_length=150) text = models.TextField() status = models.ForeignKey(Status, on_delete=models.PROTECT, default=2) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) time_create = models.DateTimeField(auto_now_add=True) time_update = models.DateTimeField(auto_now=True) def __str__(self): return self.title File permissions now haven't anything for solve the problem and I haven't any idea. I think it is simple problem, if you need more info you can request me)