Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Form inital values don't work on render
I have a model `Transaction' and ModelForm to create one : class Transaction(models.Model): """ Invoice model. Represents a basic income/outcome transaction. """ title = models.CharField(max_length=32, verbose_name="Title") category = models.ForeignKey(Category, related_name="transactions", on_delete=models.CASCADE, null=True, blank=True) operation = models.CharField(max_length=8, choices=OPERATION_TYPE, verbose_name="operation") value = models.DecimalField(max_digits=14, decimal_places=2, verbose_name="value") currency = models.CharField(max_length=3, choices=CURRENCY_CHOICE, verbose_name="currency") comment = models.CharField(max_length=255, null=True, blank=True) date_created = models.DateField(auto_now_add=True, blank=True, null=True) class Meta: verbose_name_plural = "Transactions" ordering = ["-date_created"] class NewInvoiceForm(forms.ModelForm): category = TreeNodeChoiceField(queryset=Category.objects.all()) class Meta: model = Transaction fields = ("title", "category", "operation", "value", "currency") help_texts = { "operation": _("Money spent/received. For expenses use a negative value.") } I have a Preference model linked with each user to store settings : class Config(models.Model): """ Represents user's preferences. """ user = models.OneToOneField(CustomUser, related_name="config", on_delete=models.CASCADE) currency = models.CharField(max_length=3, choices=CURRENCY_CHOICE, default=DEFAULT_SETTINGS["currency"]) language = models.CharField(max_length=56, choices=LANGUAGE_CHOICE, default=DEFAULT_SETTINGS["language"]) class Meta: verbose_name = "config" verbose_name_plural = "configs" I'm trying to get user's currency from Config model as initial value for Transaction creation form. But initial value never renders. My view : def create_transaction_view(request): if request.method == "POST": form = NewInvoiceForm( request.POST, instance=request.user ) if form.is_valid(): new_invoice = Transaction(**form.cleaned_data) # retrieving user's currency preference for further converting if income is different from base currency user_currency = request.user.config.currency # performing … -
Discretization of Multiple Time Series [closed]
I'm working on discretizing multiple time series for a project. Here's what I've done so far: I concatenated the train signals like this: [1,2,3,5] and [7,3,6,7] into [1,2,3,5,7,3,6,7]. Then, I trained a K-means ML model with the single, combined signal. Finally, I clustered all the signals with the trained model. I'm not sure if this is the right approach. I chose to concatenate the signals because the k-mean (from scikit-learn) allows inserting only a single array, so I didn't know how to feed it with multiple time series. Has anyone done something similar, or does anyone have suggestions for a better discretization method? -
Computing AUC and ROC curve with micro and macro - average on multi-class data in Scikit-Learn
I am computing and plotting AUC and ROC curves for multi-class data for the output of 3 different classifier. I want to see the difference in using micro and macro average on plotting ROC curves in a multi-class setting. I am following the code provided on scikit-lean in OvR (one versus rest) scenario. However, the macro-average ROC curves do not look right, sice some are not starting from (0,0) position. Below, graph shows the performance of Random Forest trained on 3 different augmented datasets macro-average ROC (NOT right) Whereas, the same classifier with ROC plotted using micro-average do not show the same problem. micro-average ROC curve (starts from Zero) I Have also other examples from other datasets using different classifiers (NB and DT) as the following one: macro-average ROC curve (NOT right) For plotting the curves with micro and macro average I used the following code, where: model_proba = contains aggregated predicted probabilities from a 10-CV classes = sorted(list(np.unique(y_test))) print('Sorted:',classes) n_classes = len(np.unique(y_test)) y_test_binarize = label_binarize(y_test, classes=classes) print('Binarized:',y_test_binarize) #y_test_binarize = label_binarize(y_test, classes=np.arange(classes)) scores = {} for model_name, model_proba in d_probabilities.items(): #iterating over 3 probabilities of 3 models y_pred = model_proba scores[model_name] = model_proba fpr ,tpr ,roc_auc ,thresholds = dict(), dict(), … -
Django - Moving some logic from viewsets to a model or model method in viewsets
I have a small educational project of a social network. There's a Recipes and ShoppingCart models. Besides other functionalities, RecipeViewSet allows users to download a file with the ingredients of recipes previously added to the shoppingcart. This part of the RecipeViewSet looks like this: @action( detail=False, methods=['GET'], permission_classes=[IsAuthenticated] ) def download_shopping_cart(self, request): user = self.request.user if not user.shoppingcarts.exists(): raise ValidationError('The shopping cart is empty.') return FileResponse( get_shopping_list( user_cart=user.shoppingcarts.all() ), as_attachment=True, filename='shopping list ' + dt.now().strftime('%d-%m-%Y') + '.txt', ) The function that forms the list of ingredients for downloading looks like this: def get_shopping_list(user_cart): ingredient_name = 'recipe__recipe_ingredients__ingredient__name' ingredient_unit = ( 'recipe__recipe_ingredients__ingredient__measurement_unit' ) ingredient_amount = 'recipe__recipe_ingredients__amount' amount_sum = 'recipe__recipe_ingredients__amount__sum' ingredients = user_cart.select_related('recipe').values( ingredient_name, ingredient_unit ).annotate(Sum(ingredient_amount)).order_by(ingredient_name) recipes = [f'"{recipe.recipe.name}"' for recipe in user_cart] ingredients_list = [ (f'{number}. {ingredient[ingredient_name].capitalize()} ' f'({ingredient[ingredient_unit]}) - ' f'{ingredient[amount_sum]}') for number, ingredient in enumerate(ingredients, 1) ] return '\n'.join(['Recipes:', *recipes, 'To buy:', *ingredients_list]) I want to move some of the logic (the first half of the function) that is not directly related to forming the text out of the get_shopping_list function and transfer it to a model. Therefore, my questions are, which model is better to move it to, ShoppingCart or Recipe and why? And how can this be implemented? -
Adding restriction on who can access form submission information on Wagtail CMS
I have a form page in my web application that is using Django and Wagtail. Is there a way to have a way to restrict or manage which Wagtail users can access the form submission data? Thank you So far I can't find anything that will help me answer my question rather than adding permission in the code base -
Django UserCreationForm Meta fields
I created customized usercreationform class RegisterForm(UserCreationForm): class Meta: model = Users #personal User model fields = ( "username", "first_name", "last_name", "email", "adresse", "phonenumber", ) The simple question is if it works without "password1", "password2" in fields? class RegisterForm(UserCreationForm): class Meta: model = Users #personal User model fields = ( "username", "first_name", "last_name", "email", "adresse", "phonenumber", "password1", "password2", ) if both work, what is the difference between two? -
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