Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
When trying to access files throug sftp request takes too long and hangs the server
I am using a server to store my files, and I have employed storages.backends.sftpstorage.SFTPStorage to manage URLs, downloads, and uploads. However, I occasionally encounter the following issue when I try to get files from server, causing the entire server to hang and become temporarily unavailable. My error log. My sftp configuration SFTP_STORAGE_HOST = "host" SFTP_STORAGE_ROOT = "/Files" SFTP_STORAGE_UID = 1000 SFTP_STORAGE_PARAMS = { "username": "username", "password": "password", "port": 5522, "timeout": 4, "banner_timeout": 1, "auth_timeout": 1, "channel_timeout": 4, } My view to access files: def get(self, request, name=None, *args, **kwargs): """Only for SFTP users.""" SFS = SFTPStorage() if SFS.exists(name): file = SFS._read(name) type, encoding = mimetypes.guess_type(name) response = HttpResponse(file, content_type=type) response["Content-Disposition"] = 'attachment; filename="{filename}'.format(filename=name) return response raise Http404 I tried to set timeouts, but they didn't help much. -
How to Modify Base Class to Dynamically Instantiate Appropriate Subclass Without Causing Recursion?
I am refactoring a Python class structure where I previously instantiated subclasses directly, but now I want to shift to a design where I only call a base generator class, and this base class internally decides and returns the appropriate subclass instance. However, I'm encountering a recursion problem with this new approach. My code is: class BaseGenerator: def __new__(cls, *args, **kwargs): if cls is BaseGenerator: subclass = cls._determine_subclass(*args, **kwargs) return subclass(*args, **kwargs) else: return super().__new__(cls) @staticmethod def _determine_subclass(*args, **kwargs): # Logic to determine the appropriate subclass # ... class ChildGenerator1(BaseGenerator): pass class ChildGenerator2(BaseGenerator): pass class ChildGenerator3(BaseGenerator): pass Initially, I had a structure with one base generator class (BaseGenerator) and several subclasses (ChildGenerator1, ChildGenerator2, ChildGenerator3). I used to instantiate these subclasses directly like this: generator = ChildGenerator1(...) Now, I want to only use the BaseGenerator to decide and instantiate the correct subclass. I tried implementing this logic in the new method of BaseGenerator, but this leads to a recursion issue now I'm calling the generator like this: generator = BaseGenerator(...) The problem is that when BaseGenerator redirects to a subclass, it somehow causes a recursion issue. How can I modify this approach to dynamically instantiate the correct subclass from BaseGenerator without … -
Use non standard locale code in Django i18n
Can we use a non-standard locale code in Django ? I want to use es-lat because in the film industry, the distinction is made between Spanish (es from Spain) and Latin American Spanish. So far it seems to work with this settings LANGUAGE_CODE = "fr" TIME_ZONE = "UTC" LANGUAGES = [ ("fr", _("French")), ("es", _("Spanish")), ("es-lat", _("Latin American Spanish")), ("en", _("English")), ] But this piece of code in the templates treat es-lat as es. {% get_current_language as CURRENT_LANGUAGE %} {% get_available_languages as AVAILABLE_LANGUAGES %} {% get_language_info_list for AVAILABLE_LANGUAGES as languages %} {{ languages }} # [{'bidi': False, 'code': 'fr', 'name': 'French', 'name_local': 'français', 'name_translated': 'Francés'}, {'bidi': False, 'code': 'es', 'name': 'Spanish', 'name_local': 'español', 'name_translated': 'Español'}, {'bidi': False, 'code': 'es', 'name': 'Spanish', 'name_local': 'español', 'name_translated': 'Español'}, {'bidi': False, 'code': 'en', 'name': 'English', 'name_local': 'English', 'name_translated': 'Inglés'}] -
I am running myapp\urls.py and getting an error
an error is returned the traceback is django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. I was expecting myapp\urls.py to run successfully -
Error when trying to run Python / Django project on Docker: "Server Do53:127.0.0.11@53 answered The DNS operation timed out."
I am attempting to run a Python / Django project within Docker. After running docker compose up, things start off alright but then crash out: ... web-1 | [2024-01-09 14:45:03 +0000] [158] [INFO] Booting worker with pid: 158 web-1 | [2024-01-09 14:45:03 +0000] [159] [INFO] Booting worker with pid: 159 web-1 | [2024-01-09 14:45:07 +0000] [133] [ERROR] Exception in worker process web-1 | Traceback (most recent call last): web-1 | File "/usr/local/lib/python3.9/site-packages/eventlet/support/greendns.py", line 491, in getaliases web-1 | return resolver.getaliases(host) web-1 | File "/usr/local/lib/python3.9/site-packages/eventlet/support/greendns.py", line 422, in getaliases web-1 | ans = self._resolver.query(hostname, dns.rdatatype.CNAME) web-1 | File "/usr/local/lib/python3.9/site-packages/dns/resolver.py", line 1364, in query web-1 | return self.resolve( web-1 | File "/usr/local/lib/python3.9/site-packages/dns/resolver.py", line 1321, in resolve web-1 | timeout = self._compute_timeout(start, lifetime, resolution.errors) web-1 | File "/usr/local/lib/python3.9/site-packages/dns/resolver.py", line 1075, in _compute_timeout web-1 | raise LifetimeTimeout(timeout=duration, errors=errors) web-1 | dns.resolver.LifetimeTimeout: The resolution lifetime expired after 5.402 seconds: Server Do53:127.0.0.11@53 answered The DNS operation timed out.; Server Do53:127.0.0.11@53 answered The DNS operation timed out.; Server Do53:127.0.0.11@53 answered The DNS operation timed out. I do not understand the meaning of the final error: dns.resolver.LifetimeTimeout: The resolution lifetime expired after 5.402 seconds: Server Do53:127.0.0.11@53 answered The DNS operation timed out. I am running Docker v24.0.7 on … -
How does scikit's RFECV class compute cv_results_?
From my understanding of sklearn.feature_selection.RFECV (Recursive Feature Elimination Cross Validation), you provide an algorithm which is trained on the entire dataset and creates a feature importance ranking using attributes coef_ or feature_importances_. Now with all features included, this algorithm is evaluated by cross validation. Then the feature ranked at the bottom is removed and the model is retrained on the dataset and creates a new ranking, once again assessed by cross validation. This continues until all but one feature remain (or as specified by min_features_to_select), and the final number of features chosen depends on what yielded the highest CV score. (Source) The CV score for each number of features is stored in rfecv.cv_results_["mean_test_score"], and I've been facing trouble trying to replicate these scores without using scikit's built in method. This is what I have tried to obtain the score for n-1 features, where n is the total number of features. from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import StratifiedKFold from sklearn.model_selection import cross_validate from sklearn.feature_selection import RFECV alg = DecisionTreeClassifier(random_state = 0) cv_split = StratifiedKFold(5) # train is a pandas dataframe, x_var and y_var are both lists containing variable strings X = train[x_var] y = np.ravel(train[y_var]) alg.fit(X, y) lowest_ranked_feature = np.argmin(alg.feature_importances_) … -
Database: best way to *flag a specific link* within a many-to-many relationship?
Take for example a classical student and teacher many-to-many relationship: Table "student": id, name Table "teacher": id, name Table "student_teacher": id, student_id, teacher_id, relation_quality I need to add the concept that a student has a "referent teacher": in other words, to "flag" one relation with teachers as specific, for every student. I see three possible methods: add a one-to-many relation between teacher and students add one-to-one relationship between student and student_teacher add field "is_referent" to "student_teacher", setting it to True when appropriate With option 1, the link table student_teacher is "bypassed", which in my case would require some 'constraint' against setting a teacher as referent without any relation between student and teacher through the many-to-many path. Generating SQL queries to get the corresponding "relation_quality" does not appear too hard (we would have the two required FKs at hand), but I am not sure that it would not complicate my existing Django templates; With option 2 (which I am currently using), the 'constraint' to ensure is again that a student cannot connect to a 'referent' through an entry of the link table to which she/he is not related (i.e. a link used for another student). Maybe more importantly, it "looks more … -
How to convert Django bytes data to mp3 files
I have send audid/webm bytes from react to django. And the transfered data enter image description here the code in view.py is like this def get_audio(request): audio = BytesIO(request.body) print(audio.read()) print(type(audio.read())) # os.makedirs('./data/audio.wav', exist_ok=True) # with open('./data/audio.wav', mode='bx') as f: # f.write(audio.read()) return HttpResponse("audio delievered") the request in react is like this setTimeout(() => { setRec("Stopped") const tracks = stream.getTracks(); tracks[0].stop(); mediaRecorder.stop() // console.log(chunks[0]) blobAudio = chunks[0] }, 5000); const audioUpload = () => { const fd = new FormData(); fd.append("audio_5sec", blobAudio); try{ axios.post("/uploading_audio", fd, { headers:{ 'Content-Type' : 'multipart/form-data', }, }) .then((response) => { console.log(response); }) }catch(error){ console.log(error); } } now i want to convert audio.read() bytes to mp3 in django directory and write it. How can i do this? The above comment parts doesn't work -
Django rest_framework put method doesn't obtain HTTP_AUTHORIZATION
I'm having problems with Django Rest Framework. When I'm trying to send my JWT token from React with Axios, it sent nothing... The code works for POST and GET but in PUT ... -_- The settings : CORS_ALLOW_METHODS = ( "DELETE", "GET", "POST", "PUT", ) Axios call (The token is good, so i don't sending undefined, tested): try { console.log("Ejecutando caso Exitoso"); const response = await axios.put("http://localhost:8000/empresas/empresa-persona/" + param[1], { headers: { Authorization: `Bearer ${localStorage.getItem("token")}`, 'Content-Type': 'application/json', }, }); console.log(response); } catch (error) { console.log(error); } Django function (the same function works in GET and POST , but in PUT, HTTP_AUTHORIZATION doesn't exist): def user_call_validation(request, perm): # Control de Acceso print(request.META) user = validate_user_token(token=request.META["HTTP_AUTHORIZATION"]) # print(User.objects.get(id=user["id"]).get_all_permissions()) if User.objects.get(id=user["id"]).has_perm(perm) != True: raise Exception("Acceso denegado!") -
Overriding DRF settings for tests
I'm using Python 3.9, Django 3.2, DRF 3.12.4. I'm adding JWT authentication method using simple JWT. To test my auth method, I need to set "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), I would like to avoid editing my settings file and keep all changes in my test file. That's because I have separate local and production settings, and local settings are using fake auth backend. All tests are passing when I set the above auth class in my local settings. I tried to use @override_settings: @override_settings( REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework_simplejwt.authentication.JWTAuthentication", ), } ) It seems to work fine - when I print the settings in my test: from django.conf import settings from rest_framework.settings import api_settings ... def setUp(self): print(settings.REST_FRAMEWORK) print(api_settings.DEFAULT_AUTHENTICATION_CLASSES) I get {'DEFAULT_AUTHENTICATION_CLASSES': ('rest_framework_simplejwt.authentication.JWTAuthentication',)} [<class 'rest_framework_simplejwt.authentication.JWTAuthentication'>] However, tests aren't passing - I'm getting error from my fake auth backend, as if the settings aren't getting overriden after all. I also tried editing django.conf settings directly - which is something I would rather not do, but it didn't solve my problem as well. Am I doing something wrong? Maybe my solution/tests have some logical mistakes and I'm doing something I shouldn't do? Thank you in advance for all the help. -
How to apply the sklearn OneHotEncoder to a subset of rows in a Pandas Dataframe?
I have a pandas dataframe with numerical as well as categorical columns. For any input row (to keep things simple we take any row from the orginal dataframe), I want to find the N most similar rows to it. However, instead of comparing the input row against the entire dataset I want to use a subset of the dataframe. def find_similar_rows(dataset, query_df, input_row, top_n=10): # Identify common columns common_columns = list(set(dataset.columns) & set(input_row.index)) numeric_cols = dataset.select_dtypes(include=['int64', 'float64']).columns categorical_cols = dataset.select_dtypes(include=['object', 'category']).columns _, num_imputer, cat_imputer, scaler, encoder = preprocess(dataset.copy(), numeric_cols, categorical_cols) processed_query_df, _, _, _, _ = preprocess(query_df, numeric_cols, categorical_cols, num_imputer, cat_imputer, scaler, encoder) processed_input_row, _, _, _, _ = preprocess(pd.DataFrame([input_row[common_columns]]), numeric_cols, categorical_cols, num_imputer, cat_imputer, scaler, encoder) # Calculate cosine similarities cosine_similarities = cosine_similarity(processed_input_row, processed_query_df)[0] # Combine cosine similarity with DOMAIN_WEIGHTED_SUM and normalized RECHNUNGS_MENGE combined_scores = cosine_similarities + processed_query_df['DOMAIN_WEIGHTED_SUM'].values / 100 + processed_query_df['RECHNUNGS_MENGE'].values / RECHNUNGS_MENGE_NORMALIZATION_FACTOR # Get indices of top similar rows based on combined_scores top_indices = np.argsort(combined_scores)[::-1][:top_n] # Return both indices and scores return top_indices, combined_scores[top_indices] def preprocess(df, numeric_cols, categorical_cols, num_imputer=None, cat_imputer=None, scaler=None, encoder=None): # Check if the imputers and scaler are provided, if not, create new ones if num_imputer is None: num_imputer = SimpleImputer(strategy='mean') df[numeric_cols] = num_imputer.fit_transform(df[numeric_cols]) else: df[numeric_cols] … -
I encountered this error "UNIQUE constraint failed: accounts_user.username" while trying to register a user in my django project
I tried registering a user for the first time in Django but it was giving me this error IntegrityError at /register/ UNIQUE constraint failed: accounts_user.username Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 4.2.6 Exception Type: IntegrityError Exception Value: UNIQUE constraint failed: accounts_user.username Exception Location: C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib\site-packages\django\db\backends\sqlite3\base.py, line 328, in execute Raised during: accounts.views.register Python Executable: C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\python.exe Python Version: 3.12.0 Python Path: ['C:\Users\Joseynice\Desktop\task_file', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\python312.zip', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\DLLs', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312', 'C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib\site-packages'] Server time: Tue, 09 Jan 2024 14:21:19 +0000 I tried registering a user in Django see the error below` File "C:\Users\Joseynice\AppData\Local\Programs\Python\Python312\Lib\site- packages\django\db\backends\sqlite3\base.py", line 328, in execute return super().execute(query, params) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ django.db.utils.IntegrityError: UNIQUE constraint failed: accounts_user.username [09/Jan/2024 15:25:43] "POST /register/ HTTP/1.1" 500 159087 #accounts.model from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin # Create your models here. class UserManager(BaseUserManager): def create_user(self, email, password1=None, **extra_fields): if not email: raise ValueError('The Email field must be set') email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password1) user.save(using=self._db) return user def create_superuser(self, email, password1=None, **extra_fields): extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) return self.create_user(email, password1, **extra_fields) class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(verbose_name="email", max_length=60, unique=True) first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) username = models.CharField(max_length=60, unique=True) date_joined = models.DateTimeField(verbose_name="date joined", auto_now_add=True) last_login = models.DateTimeField(verbose_name="last login", auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) … -
Cannot insert into a generataed always identity column in Django ModelForm
I have a table 'Orders' in Oracle database which have a column 'order_id' as primary key and is set to auto generate Ids. Then I have remaining columns like order_date, received_from ,quantity,delivery_date etc..Now I am using a ModelForm 'OrderForm' for adding new orders and updating if order accordingly. Now the problem is I am able to update the order table using orderform for a particular order using order_id, but when I try to add a new order, then it throw error saying cannot insert in to a generated always identity column. I understand that here that django is trying to insert a null value into auto generated column order_id. I actually want to just ignore 'order_id' field and insert other details to the table. I am new to django. Please help. Thanks. -
Custom form in the Django Admin: how to make it look the same as the Django's Admin forms?
I have Django application which handles license codes, so there's a model and a modeladmin, and that all works. But I want to add a custom page to the admin interface to generate a whole bunch of license codes and while everything is working, it looks really bad. So first of all to get a new button in the top right, I have a custom change_list.html template for this specific model: {% extends "admin/change_list.html" %} {% block object-tools-items %} {{ block.super }} <li><a href="generate/" class="addlink">Generate Codes</a></li> {% endblock %} This makes the extra button show up: Clicking on that button opens a new page, which I created with this code: @admin.register(RedeemCode) class RedeemCodeAdmin(admin.ModelAdmin): # [...the usual admin config...] def get_urls(self): return [ path("generate/", self.admin_site.admin_view(self.generate_codes), name="generate-codes"), ] + super().get_urls() def generate_codes(self, request): class GenerateCodeForm(forms.Form): product = forms.ModelChoiceField(queryset=ProductVariant.objects.all()) partner = forms.ModelChoiceField(queryset=Partner.objects.all()) comment = forms.CharField() count = forms.IntegerField(min_value=1, initial=1) for_email = forms.CharField() export_csv = forms.BooleanField(required=False, label="Export generated codes to CSV") if request.method == "POST": form = GenerateCodeForm(request.POST) if form.is_valid(): print(form.cleaned_data) return HttpResponseRedirect("/admin/shop/redeemcode/") context = dict( # Include common variables for rendering the admin template. self.admin_site.each_context(request), opts=RedeemCode._meta, title="Generate Codes", form=GenerateCodeForm(), ) return TemplateResponse(request, "admin/shop/redeemcode/generate_codes.html", context) And my generate_codes.html template: {% extends "admin/base_site.html" %} {% … -
how to create django rest asynchronous APIView
I have an ecommerce website developed using django rest framework version 3.14. In some days of month, we have a huge traffic of users trying to order. As the number of requests in some specific times are so big, a few of them will fail. I think one solution is to use asynchronous APIs in backend. The views in django back are class based APIView. And I can not figure out how should I change the simple APIViews to Async views. I also don't need to change all views, but 2 views that are handling purchase process. In these 2 views, I have post and get methods, and some other methods that handle ORM calls (filter, get, all, etc.) Any solution? -
Skipping of tests in pytest using the command line
I've tried to skip tests in pytest according to this: https://docs.pytest.org/en/latest/example/simple.html#control-skipping-of-tests-according-to-command-line-option When I try to run the tests using only the command pytest, the marked tests are skipped as intended. But when I run the tests with pytest --runslow I get the following error: ERROR: usage: pytest [options] [file_or_dir] [file_or_dir] [...] pytest: error: unrecognized arguments: --runslow inifile: /app/pyproject.toml rootdir: /app My tests are in project/myapp/tests/tests.py and the conftest file in project/conftest.py. How can I make pytest recognized my command line argument? -
I am trying to import views.py to urls.py using from . import views but I keep getting an import erroe
from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("", views.home), path("predict/", views.predict), path("predict/result", views.result) I expected to run urls.py successfully -
I want 1st field to be not equal to 2nd field (both fields are foreign key to same model)
I am trying to raise validation error when my 'reference' field is same as 'contact', but def clean won't work. Here is my code: class FacultyRegistration(models.Model): role = models.ForeignKey(Roles, on_delete=models.CASCADE, null=True, verbose_name="Faculty Role") contact = models.OneToOneField('Contacts.Contact', related_name='faculty_Contact', unique=True, on_delete=models.CASCADE) reference = models.ForeignKey('Contacts.Contact', on_delete=models.CASCADE, related_name='faculty_reference',) # I tried def clean but it wont work def clean(self): if self.contact == self.reference: raise ValidationError('Primary and secondary inclinations should be different.') def __str__(self): return f"{self.contact} ({self.role})" class Meta: verbose_name = "Faculty Management" verbose_name_plural = "Faculty Managements" -
CSS styling not applying to Dockerized Django project
I created a django project, life was good. However when I dockerized it everything else works fine apart from the css styling. Below is my dockerfile, let me know any other information I can provide FROM python:3.8 WORKDIR /app COPY . /app RUN pip install -r requirements.txt EXPOSE 8000 ENV NAME World RUN python manage.py collectstatic --noinput CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"] I feel like ive tried everything but nothing will make these pesky css files appear in my image -
No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context
I have an appengine app that works with python2.7 and I want to migrate to python3.9. I started by making call to google ndb cloud inside my appengine app. I am using python3.9 and django as a web framwork. This is my code: from django.shortcuts import render,redirect from google.cloud import ndb class Book(ndb.Model): title = ndb.StringProperty() client = ndb.Client() def get_books(): with client.context(): books = Book.query() return books def main(request): return HttpResponse(get_books()) And this is the traceback File "/Users/hizan/Desktop/venvdjango/lib/python3.9/site-packages/google/cloud/ndb/query.py" in wrapper 1213. context = context_module.get_context() File "/Users/hizan/Desktop/venvdjango/lib/python3.9/site-packages/google/cloud/ndb/context.py" in get_context 118. raise exceptions.ContextError() Exception Type: ContextError at / Exception Value: No current context. NDB calls must be made in context established by google.cloud.ndb.Client.context. -
Django : How to fill Charfield with the button value
I'm building a simple python webapp that stacks 2 tables. First the columns of both tables are listed as buttons on top of the page (lets call it column buttons). Next we have input field row (with 2 inputs), Input 1 --> The columns to be stacked, separated by commas. Input 2 --> The column name of the Output table. i.e each row represents a column-combination. I'm good until here. Challenge: I want to auto-fill Input 1 (with the column names) while I click the respective column buttons. Instead of typing it manually I'm unable to find the options in Django to achieve this yet. Many thanks in advance -
401 Unauthorized when authenticating with token in Django
I'm working on a Django project where users are required to verify their phone number on their first login. Once their phone number is verified, a token is assigned to them. However, when I try to authenticate with the token in my tests, I get a 401 unauthorized error. Does anyone know where the problem might be? r = client.patch("/user/", data= dict(pk=1), format='json', headers= dict(Authorization=f"Token {user.auth_token.key}")) assert r.status_code == 200 -
Why is my hx-trigger not triggered using from: <css selector>?
I have a button that I want to send two requests to the server when clicking. The setup is like this: <button id="add-item" hx-get="some-url" hx-trigger="click" hx-target="#item-form" hx-swap="beforeend" type="button">Add item</button> <br> <div hx-get="some-other-url" hx-trigger="from: #add-item" hx-swap="beforeend"> </div> I have tried using hx-trigger="click from: #add-item but that does not work either. The first request sent by add-item is fetched from the server correctly, but the second one from the div is never sent at all. When changing the trigger for the div to something like hx-trigger="click", it works (also needing some content inside it to click). Is there soemthing wrong with the syntax or why would this not work? I have imported HTMX like so: <script src="https://unpkg.com/htmx.org@1.9.10" integrity="sha384-D1Kt99CQMDuVetoL1lrYwg5t+9QdHe7NLX/SoJYkXDFfX37iInKRy5xLSi8nO7UC" crossorigin="anonymous"></script> Any help would be appreciated. -
Django verification email
I have a Django app deployed on Pythonanywhere. Everything works as expected except for the verification emails.When a new user registers, he should receive a verification email, but Django doesn't send it until the admin panel is reloaded. All other emails(welcome emails, contact form emails) are sent without issue. When I test locally on my laptop verification emails are sent instantly. I am using django-email-verification and emails are sent through gmail. views.py class RegisterView(CreateView): form_class = RegisterForm template_name = 'common/register.html' success_url = reverse_lazy('login') def dispatch(self, request, *args, **kwargs): if request.user.is_authenticated: return redirect('index') return super().dispatch(request, *args, **kwargs) def form_valid(self, form): form.save(commit=False) user_email = form.cleaned_data['email'] user_username = form.cleaned_data['username'] user_password = form.cleaned_data['password1'] user = UserModel.objects.create_user(username=user_username, email=user_email, password=user_password) user.is_active = False send_email(user) return HttpResponseRedirect(reverse('email sent')) def form_invalid(self, form): return super().form_invalid(form) -
Django admin: group two fields in a section without having to specify every other field as well?
I have a Django model with a whole bunch of fields. In the Admin UI I want to group two of these fields in their own little section, but as far as I know that means I now have to specify every single model field in the fieldsets config: @admin.register(MyModel) class MyModelAdmin(admin.ModelAdmin): fieldsets = ( ( None, { "fields": ("field_1", "field_2", "field_3") # etc etc } ), ( "My special section", { "fields": ("field_11", "field_12") } ) ) It's annoying to copy and paste so many field names, but worse: if I add a new field to the model I have to remember to add it to the fieldsets config as well. So my question is: is there no way to have some kind of "the rest of the fields go here" section? Or another way to only change the section of a subset of fields while leaving the rest alone?