Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Model.objects.create vs Model.save()
New to Django ORM and had a small question. If I have a model like: class Person(models.Model): id = models.BigAutoField(primary_key=True) name = models.CharField(max_length=255) I can add a new person in the following ways: p1 = Person.objects.create(name="Bob") or p2 = Person(name="Bob") p2.save() In the first case (p1), I can expect that the "id" field is set (auto-incremented when insertion is done). Can I expect the same in the second case? Does django update the in-memory "Person" object's properties (in this case the id field) once a save is done? Follow-up questions: Let's say I had another model class Business(models.Model): id = models.BigAutoField(primary_key=True) owner = models.ForeignKey(Person) Does it make a difference if I do b = Business(owner=p1) b.save() vs b = Business(owner=p2) b.save() What happens if I don't save or create the person object before passing it into Business? e.g. p = Person(name="Bob") b = Business(owner=p) b.save()? -
Django app profile page still showing after logging out
I am trying to set up a profile page for users. Although when I logout and go to the profile page url("127.0.0.1:8000/profile"), it is still showing the result of the user(with which I logged in) views.py: def login_user(req): if req.method == 'POST': form = AuthenticationForm(data=req.POST) if form.is_valid(): user = form.get_user() login(req, user) return redirect('http://127.0.0.1:8000/') else: form = AuthenticationForm() return render(req, 'loginpage.html', {'form': form}) def logout_user(req): if req.method=='POST': logout(req) return redirect('home') @login_required def profile_page(req): user = req.user user_profile, created = UserProfile.objects.get_or_create(cur_user=user) return render(req, 'profilepage.html', {'user': user, 'user_profile': user_profile}) @login_required def edit_bio(req): if req.method == 'POST': new_bio = req.POST.get('bio') user_profile = req.user.userprofile user_profile.bio = new_bio user_profile.save() return redirect('profile_page') urls.py: from django.urls import path from django.contrib.staticfiles.urls import staticfiles_urlpatterns from . import views urlpatterns = [ path('', views.homepage, name='home'), path('signup/', views.signup, name='signup'), path('login/', views.login_user, name='login'), path('profile/', views.profile_page, name='profile_page'), path('profile/edit/', views.edit_bio, name='edit_bio'), path('logout/', views.logout_user, name='logout'), ] urlpatterns += staticfiles_urlpatterns() What can be the problem here? -
Django ASGI vs WSGI performance
I am trying to test the performance difference in ASGI and WSGI servers when there are i/o bound functions. I am going to receive streaming responses from 3rd party APIs and then stream them back to client, I am planning on using StreamingHttpResponse of Django. I created two test views, one async one sync, and used time.sleep and asyncio.sleep functions to simulate these web requests that will take a long time to complete. This is the async view: async def async_view(request): async def generate_response_data(): for i in range(10): await asyncio.sleep(1) yield f'{i} ' response = StreamingHttpResponse( generate_response_data(), content_type='text/event-stream' ) return response And this is the sync view: def sync_view(request): def generate_response_data(): for i in range(10): time.sleep(1) yield f'{i} ' response = StreamingHttpResponse( generate_response_data(), content_type='text/event-stream' ) return response I tried to load test these two endpoints to see the performance difference. I ran sync view with Django's builtin development server and async view with uvicorn. I used apache benchmarking tool for load testing. I used this command ab -c 500 -n 1000 <endpoint> meaning 500 concurrent request and total of 1000 requests. ASGI server resulted in 35 requests per second, and WSGI server 42 requests per second. Every article I read … -
Passing a function into context
I'm trying to do what this Article says, and the answer says to simply create a function to do this. How would I go about that? I have tried creating a function that gets the requests from the form and getting the foreign key with the same id but I can not seem to make it work. models.py ``` class Categories(models.Model): category_name = models.CharField(max_length=100, unique=True) description = models.TextField(max_length=300, blank=True) class Meta: verbose_name_plural = 'Categories' def __str__(self): return self.category_name class Product(models.Model): product_category = models.ForeignKey(Categories, on_delete=models.SET_NULL, null=True, related_name='categories', blank=True) title = models.CharField(max_length=100) description = models.TextField(max_length=250) price = models.DecimalField(max_digits=12, decimal_places=2) stock = models.IntegerField(default=0) created_at = models.DateTimeField(auto_now_add=True) class Meta: verbose_name_plural = 'Products' unique_together = ['title', 'product_category'] def __str__(self): return self.product_category.category_name + '-' + self.title views.py class ProductUpdateView(UpdateView): model = Product template_name = 'products/product_update.html' form_class = ProductForm # success_url = reverse_lazy('products_list') context_object_name = 'products' object = Product.objects.all() #Trying to get the specific id def preselect(self): prod_cat = self.request.POST.get('product_category_id') pre_select = Categories.objects.get(id=prod_cat) final_preselect = pre_select.id return final_preselect # def form_valid(self, request): # if 'Delete' in self.request.POST: # reverse_lazy('products_list', kwargs={'pk': object.pk}) # else: # self.object = request.save() # return HttpResponseRedirect(self.get_success_url()) extra_context = {'preselect': preselect, 'category_context': Categories.objects.all()} def get_success_url(self): if 'categories/' in self.request.path: the_pk = self.request.POST.get('product_category') category = … -
django template: floatformat filter not working when used within an if-condition
In my template, I have: {% if subject.market_value_increase_pct > subject.neighborhood_increase_pct %} Values provided are: market_value_increase_pct = 8.6 & neighborhood_increase_pct = 10.5 I expect the if-condition should evaluate to false with these values. However, it was evaluating to true and the code block within the if-condition was being executed. My thought was may be the variables are being considered as strings, in which case it would evaluate to true. So, I tried to force convert the values to float using floatformat and then compare: {% if subject.market_value_increase_pct|floatformat > subject.neighborhood_increase_pct|floatfomat %} But, that isn't working. It still evaluates to true. The floatformat filter works outside of the if-condition though: <td>{{ subject.market_value_increase_pct|floatformat }}%</td> As per Django template docs, using filters in if-condition is permitted. Would appreciate if anyone can point out what I am missing. Below is the complete code block: {% if subject.market_value_increase_pct|floatformat > subject.neighborhood_increase_pct|floatfomat %} <tr> <th>Subject's market value last year:</th> <td>{{ subject.market_value_last_year | currency | remove_decimal_point}}</td> </tr> <tr> <th>Percent increase:</th> <td>{{ subject.market_value_increase_pct|floatformat}}%</td> </tr> <tr> <th>Average percentage increase for state class {{subject.state_class}} in neighborhood {{ subject.neighborhood_code }}:</th> <td>{{ subject.neighborhood_increase_pct|floatformat}}%</td> </tr> {% endif %} I tried using add:"0" and int filters also. None of them work. Basically, filters aren't working within if-condition … -
How can I get my PostgreSQL server to wrok?
Total spawn time to start the pgAdmin4 server: 0.017 Sec 2023-07-26 18:16:20,262: WARNING werkzeug: WebSocket transport not available. Install simple-websocket for improved performance. Serving Flask app 'pgadmin' Debug mode: off 2023-07-26 18:16:20,262: WARNING werkzeug: Werkzeug appears to be used in a production deployment. Consider switching to a production web server instead. An attempt was made to access a socket in a way forbidden by its access permissions It says PgAdmin 4 server could not be contacted. I tried deleting, uninstalling still nothing. I'm using windows 11. PosgtreSQL 15. I used the pgAdmin 4 that comes with it. I then deleted the pgAdmin 4 and downloaded pgAdmin 4 7v4. It started but it doesn't connect. As for the installation process, I installed directly from the postgreSQL app with the installer and followed all the right steps. -
Merge two values from form.Model in defined CharField
I try to merge two values from dropdown "on the fly" to a HTML input field model.py class ProjectID(models.Model): project_id = models.CharField(max_length=120, unique=True) def __str__(self): return self.project_name class ProjectName(models.Model): project_name = models.CharField(max_length=120, unique=True) def __str__(self): return self.project_name class Project(models.Model): combine_name = models.CharField(max_length=50, unique=True) project_id = models.ForeignKey(ProjectID, related_name='p_number', on_delete=models.CASCADE) project_name = models.ForeignKey(ProjectName, related_name='p_name', on_delete=models.CASCADE) def __str__(self): return f"{self.project_id}_{self.project_name}" views.py class AddProject(generic.FormView): template_name = 'project/project-add.html' form_class = ProjectAddForm success_url = reverse_lazy('project:project-dashboard') urls.py urlpatterns = [ path('', views.dashboard, name='project-dashboard'), path('add/', views.AddProject.as_view(), name='project-add') ] forms.py: class ProjectAddForm(forms.ModelForm): class Meta: model = Project fields = ['project_id', 'project_name', 'combine_name'] project-add.html {% block main-body %} <div class="container"> <form method="post" class="form card p-3 mt-5"> {% csrf_token %} <div class="row align-items-start"> <div class="col-md-4" id="option_a"> {{ form.project_id|as_crispy_field }} </div> <div class="col-md-4" id="option_b"> {{ form.project_name|as_crispy_field }} </div> </div> <div class="row align-items-center"> <div class="col-md-8">{{ form.combine_name|as_crispy_field }}</div> </div> {% endblock main-body %} I try to merge form.project_id form.project_name if the dropdowns are selected and appears into the field form.combine_name With jquery the result failed because I guess it's not possible to handle with templatetags $('#option_a, #option_b').change(function() { var val = $('#option_a').val() + $('#option_b').val(), new_price; $("#new_option").text(val); -
How unable to run pipenv install due to python version incompatibility
I imported a python folder that came with Pipfile and Pifile.lock in it. I tried to run pipenv install in my VScode terminal window but I got a warning saying: "Warning: Python 3.9 was not found on your system... Neither 'pyenv' nor 'asdf' could be found to install Python". I was expecting pipenv install to install the application dependencies and then create a virtual environment which I can go into using pipenv shell. But all to no avail. In my machine, I have python 3.11.4. Would downgrading the version of my machine to python 3.9 solve the problem? or is there a better way to go about this? Looking forward to your assistance. Thanks -
Order management system in the ecommerce website
The problem is about the logic of the implementation of an order management system in an ecommerce website I try to implement an order management system using django in an ecommerce website can anyone help me in the implementation of the oms in the ecommerce website using stripe and paypal in the process of the payement -
The local server can't reach the statics files with app engine
Im following the Running Django on the App Engine standard environment guide but at the step where I can launch the local server using python manage.py runserver using the Google secret and proxy the local files are giving a 404 error. However, when I deploy the app it works perfectly. I ran manage.py collectstatic and I try to modify the app.yaml but it didn't work. this the structure of the project : ├── app.yaml ├── cloud-sql-proxy ├── config │ ├── __init__.py │ ├── __pycache__ │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqllite3 ├── home │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── __init__.py │ ├── migrations │ ├── models.py │ ├── __pycache__ │ ├── static │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── main.py ├── manage.py ├── noxfile_config.py ├── README.md ├── requirements-test.txt ├── requirements.txt ├── static │ ├── admin │ └── home ├── templates │ └── registration and the home/static/ look like this home/static └── home ├── cgv.pdf ├── css ├── font ├── img ├── js the settings.py contain : STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = "/static/" STATICFILES_DIRS = [] the static files are called like this in the … -
how to use subquery or parent query in prefetch queryset in django
Class User(models.Model): buyer = models.OnetoOne( "payments.Buyer", on_delete=models.SET_NULL, related_name="user", null=True, blank=True ) class Order(models.Model): test = models.ForeignKey("itests.Test", on_delete=models.SET_NULL, null=True, default=True, related_name="orders") buyer = models.ForeignKey( "payments.Buyer", on_delete=models.SET_NULL, related_name="orders", null=True, blank=True ) class Sessions(models.Model): test = models.ForeignKey("itests.Test", on_delete=models.SET_NULL, null=True, default=True, related_name="sessions") user = models.ForeignKey( "payments.User", on_delete=models.SET_NULL, related_name="user_sessions", null=True, blank=True ) Sessions.objects.filter(valid=True).prefetch_related('user__buyer__orders') will prefech user's buyer relation orders and Sessions.objects.valid().prefetch_related('test__orders') will fetch only test orders but i need only objects or orders which are belong to same session user and same test in single query like tss.prefetch_related(Prefetch('user__buyer__orders',queryset=Order.objects.filter(test=F('test'), buyer=F('user__buyer')))) buyer orders should be the same session test -
How to send a http response and then execute code, all inside a function?
I'm using Django and I have set a webhook for some events that I need to receive. How can i run some code after sending a response? Something like in this pseudo-code: def my_webhook(request): # doing some stuff yield HttpResponse('200') # doing some other stuff Does it make sense to use a request_finished signal to do this? In the django docs I see that when possibile it should be better to avoid signals -
Argument missing
Using: Django/Python I'm trying to delete files... it's showing this error: TypeError at /deletar_arquivo/18/ DeletarArquivoAnamnese() missing 2 required positional arguments: 'pk' and 'id_anamnese'. template: {% if arquivos_anamnese %} <section class="row width-100 d-flex ver-anamnese-info-queixa"> <main class="col-xxl-12 width-100 d-flex flex-column"> <div class="row mt-2 d-flex mt-width-100 ver-anamnese-info-queixa-perg"> {% for arquivo in arquivos_anamnese %} <div class="col-md-1"> <a class="arquivos-ver-anamnese-box" href="{{ arquivo.arquivo.url }}" target="_blank"> {% if arquivo.arquivo|is_pdf %} <img class="arquivos-ver-anamnese-pdf" src="{% static 'icons/pdf.png' %}" alt="{{ arquivo.arquivo.name }}"> {% else %} <img class="arquivos-ver-anamnese-img" src="{{ arquivo.arquivo.url }}" alt="{{ arquivo.arquivo.name }}"> {% endif %} </a> <form method="post" action="{% url 'deletar_arquivo' arquivo_id=arquivo.id %}"> {% csrf_token %} <button type="submit" class="delete-arquivo-ver-anamnese"><i class="fi fi-sr-cross-circle"></i></button> </form> </div> {% endfor %} </div> <div class="space-px"></div> <div class="space-px"></div> </main>{# col #} </section> {% endif %} views: def VerAnamnese(request, pk, id_anamnese): cliente_anamnese = get_object_or_404(Cad_Clientes, pk=pk) form_anamnese = get_object_or_404(Anamnese, id_anamnese=id_anamnese, id_paciente=cliente_anamnese) if form_anamnese.exame_sin_vitais_altura and form_anamnese.exame_sin_vitais_peso: imc = calcular_imc(peso=form_anamnese.exame_sin_vitais_peso, altura=form_anamnese.exame_sin_vitais_altura) else: imc = "" # define um valor nulo para o imc if form_anamnese.exame_sin_vitais_altura: alt = cm_m(form_anamnese.exame_sin_vitais_altura) print(alt) else: alt = "" # Recupere os objetos ArquivosAnamnese associados à instância de form_anamnese arquivos_anamnese = ArquivosAnamnese.objects.filter(Anamnese_arquivo=form_anamnese) return render(request, "base/base_ver_anamnese.html", {'cliente': cliente_anamnese, 'form': form_anamnese, 'imc': imc, 'altura': alt, 'arquivos_anamnese': arquivos_anamnese, 'id_anamnese': id_anamnese}) def DeletarArquivoAnamnese(request, arquivo_id, pk, id_anamnese): cliente_anamnese = get_object_or_404(Cad_Clientes, pk=pk) form_anamnese … -
Wagtail autogenerated slug with id
I want to create PersonPage without title field, but with fields “surname” and “name” and also I want it to generate slug (at saving) “surname-name-id” where “id” is private key (id, or page_ptr_id) from database. What should I use to solve that issue? I tried to create custom form and make class PersonPage based on that form — it helped me get rid of title, but I have no access to id -
django-import-export "Errors: line number : 1 - 'id' " - "KeyError: id"
I have a model for driving schools in Denmark. When I try to import them form and .xlsx file, I get the following error: Errors Line number: 1 - 'id' 43959328, 2023-03-20, None, Autoskolen.com ApS, Langgade 3 - 4262 Sandved, 4262, Sandved, Anpartsselskab, 855300 Køreskoler, None, None, Nej, None, None, 1 Traceback (most recent call last): File "C:\PATH\lib\site-packages\import_export\resources.py", line 713, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\PATH\lib\site-packages\import_export\resources.py", line 375, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\PATH\lib\site-packages\import_export\resources.py", line 362, in get_instance import_id_fields = [ File "C:\PATH\lib\site-packages\import_export\resources.py", line 363, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'id' I am using the import_export package for the import. This is how my code looks like: admin.py: from import_export.admin import ImportExportModelAdmin from django.contrib import admin from .models import Koereskoler #Post class KoereskoleAdmin(ImportExportModelAdmin, admin.ModelAdmin): ... admin.site.register(Koereskoler, KoereskoleAdmin) models.py: from django.db import models from datetime import date from django.core.validators import RegexValidator from django.utils import timezone from django.contrib.auth.models import User def default_user(): return User.objects.get(id=1).pk class Koereskoler(models.Model): **CVR_nummer = models.IntegerField(unique=True, primary_key=True, default=00000000)** startdato = models.DateField(default=timezone.now) ophoersdato = models.CharField(max_length=255, blank=True, null=True) navn = models.CharField(max_length=255) adresse = models.CharField(max_length=255) postnr = models.IntegerField(default=0000) by = models.CharField(max_length=50, null=True) virksomhedsform_type_choices = ( ('Enkeltmandsvirksomhed', 'Enkeltmandsvirksomhed'), ('Anpartsselskab', 'Anpartsselskab'), ('Aktie', 'Aktie'), ('Interessentskab', 'Interessentskab'), ('Andelsselskab … -
Python/Django: Custom user model doesn't get saved to database when submitting a form
so I am experimenting with custom user models in Django for a school project. I created some custom fields inheriting from the AbstractUser class, wrote a custom UserManager and registered the model in the admin page, finally rendering a template from a form which extends the UserCreationForm and uses my CustomUser as a model(which all seems to work fine, all the fields are visible in the admin, also in adding and detail view). Also I can add users directly from the admin page, that is working fine. However, when I submit the form, I get redirected and get [26/Jul/2023 13:10:40] "POST /register/ HTTP/1.1" 302 0 in the terminal but the user is not saved in the database. Following you can find my files. models.py import datetime from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomUserManager(BaseUserManager): def create_user(self, email, password, first_name, last_name, birth_date, credit_card, **extra_fields): email = self.normalize_email(email) user = self.model(email=email, first_name=first_name, last_name=last_name, birth_date=birth_date, credit_card=credit_card) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): extra_fields.setdefault("is_staff", True) extra_fields.setdefault("is_superuser", True) extra_fields.setdefault("is_active", True) if extra_fields.get("is_staff") is not True: raise ValueError(_("Superuser must have is_staff=True.")) if extra_fields.get("is_superuser") is not True: raise ValueError(_("Superuser must have is_superuser=True.")) … -
How to show value from choices in react native?
I have a react native app and I am using django for the backend. And I try to display a selected dropdown choice from the django app in the reac native app. Django backend: So I have this part of model: pet_list = models.CharField(max_length=2, choices=PetChoices.choices, default=PetChoices.EMPTY, verbose_name="Huis- en Hobbydierenlijst") description = models.TextField(max_length=1000, blank=True, null=True, verbose_name="Beschrijving") and serializer: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = ['id', 'name',"sort", "sc_name", "uis", "cites", "pet_list", 'description', "feeding", "housing", "care", "literature", 'images', 'category'] def get_animal(self, obj): return obj.get_animal_display() and for react. I am using a accordion: <List.Accordion title="Hobbydierenlijst" expanded={LegislationExpanded} onPress={() => setLegislationExpanded(!LegislationExpanded)}> <Text>{item.pet_list}</Text> </List.Accordion> <List.Accordion title="Beschrijving" expanded={ReviewExpanded} onPress={() => setReviewExpanded(!ReviewExpanded)}> <Text>{item.description}</Text> </List.Accordion> And I am using the Accordion in this component: export const SubCategoryScreen = ({ route, navigation }) => { const [subCatgoryList, setSubCategoryList] = useState([]); const [isLoading, setLoading] = useState(true); const [searchAnimal, setSearchAnimal] = useState(""); //accordion const { toggle, showAccordion } = useContext(ToggleContext); const { accordionItems } = useContext(AccordionItemsContext); const handleSearch = (query) => { setSearchAnimal(query); }; const filteredData = subCatgoryList.filter((item) => item.name.toLowerCase().includes(searchAnimal.toLowerCase()) ); useEffect(() => { fetchSubCategoryData(route.params.subcategories).then((data) => { if (data.animals.length > 0) { setSubCategoryList(data.animals); setLoading(false); } else { setSubCategoryList(data.subcategories); setLoading(false); } }); }, [route]); return ( <SafeArea> {isLoading && ( <LoadingContainer> … -
I have renamed my csrftoken using django's CSRF_COOKIE_NAME, I made similar changes in front end. But X-CSRFToken is missing in req headers
I am using two django instances. Both of them are setting the same csrftoken variable, which is causing conflicts. One of the csrftoken cookie is overwritten by other csrftoken cookie. So I am getting CSRF Failed: CSRF token missing or incorrect.. -
Not always sometime getting the "Forbidden (403) CSRF verification failed. Request aborted." Error in Django web application
I have one login form in Django template as given below:- <form action="{% url 'doLogin' %}" class="form-group" method="post"> {% csrf_token %} <div class="row"> <input type="text" name="username" id="username" class="form__input" placeholder="Username" required> </div> <div class="row"> <!-- <span class="fa fa-lock"></span> --> <input type="password" name="password" id="password" class="form__input" placeholder="Password" required> </div> <div class="row"> <input type="submit" value="Submit" class="btn"> </div> </form> The view Functions are defined as given below:- def loginUser(request): return render(request, 'login_page.html') def doLogin(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) return redirect('dashboard') else: messages.error(request, 'Invalid Login Credentials!! Remember Username and Password are case sensitive!!!') return render(request, 'login_page.html') In settings.py file I have included following parameters with value given below:- ALLOWED_HOSTS = ['gyanbharatimau.co.in'] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', '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', ] SESSION_EXPIRE_AT_BROWSER_CLOSE = True CSRF_TRUSTED_ORIGINS = ['https://gyanbharatimau.co.in'] Now its working fine in development as well as in production environment. But sometime in production environment (Not always I guess 2 or 3 times daily) login attempt is failing with following error message:- Forbidden (403) > CSRF verification failed. Request aborted. When i enabled the debug in production i am getting following details:- Help Reason given for failure: CSRF token … -
Why django cant find a photo?
i wrote in html file, django cant find a photo this is a media files structure class Recipe(models.Model): title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) photo = models.ImageField(upload_to="photos/%Y/%m/%d/", default=None, verbose_name="Фото") ingredients = models.TextField(null=True, blank=True) directions = models.TextField(null=True, blank=True) def __str__(self): return self.title maybe problem in models On site i see img icom instead full image -
Django Validators not working in shell command
Django Validators not working in shell command, it works just on Django Forms and Django Admin but not in shell commands. I have this: Validator def validate_cuit(value): """ Must be exactly 11 numeric characters """ if len(value) != 11: raise CuitValidationException('CUIT should have 11 characters') if not value.isdigit(): raise CuitValidationException('CUIT should only contain numeric characters') return value Exception class CuitValidationException(ValidationError): pass Model class Empresa(models.Model): name = models.CharField(max_length=120, validators=[validate_name]) cuit = models.CharField(max_length=11, validators=[validate_cuit]) If I do this, I get no error e = Empresa.objects.create(name="Testing Case", cuit='1') The only way I found to solve this is by working on the save method: def save(self, force_insert=False, force_update=False, using=None, update_fields=None): self.name = validate_name(self.name) self.cuit = validate_cuit(self.cuit) return super().save(force_insert, force_update, using, update_fields) But I'm sure it shouldn't be neccesary, can you help me with this? -
Dynamically modifying fields in django Rest Framework
Okay so I have two classes one is Book and the other one is Category. Book and Category are linked by a foreign key named category which is a Book field. See the code class Category(models.Model): class Meta: verbose_name_plural = "Categories" category = models.CharField(max_length=20) def __str__(self): return self.category class Book(models.Model): book_title = models.CharField(max_length=20) category = models.ForeignKey(Category, on_delete=models.CASCADE) def __str__(self): return self.book_title And below are the serializer classes class DynamicFieldsModelSerializer(serializers.ModelSerializer): """ A ModelSerializer that takes an additional `fields` argument that controls which fields should be displayed. """ def __init__(self, *args, **kwargs): # Don't pass the 'fields' arg up to the superclass fields = kwargs.pop('fields', None) # Instantiate the superclass normally super().__init__(*args, **kwargs) if fields is not None: # Drop any fields that are not specified in the `fields` argument. allowed = set(fields) existing = set(self.fields) for field_name in existing - allowed: self.fields.pop(field_name) class CategorySerializer(DynamicFieldsModelSerializer): class Meta: model = Category # only show the category field fields = ['category'] class BookSerializer(serializers.ModelSerializer): # this will show the category data which is related to this Book category = CategorySerializer() class Meta: model = Book fields = '__all__' And now I want that when I get the data of the book using @api_view, I should … -
AWS update TLS version from tls1.1 to tls1.2 in django using SES smtp
Recently I have received an email from AWS that has identified few endpoints using AWS SES for sending mails. We have identified TLS 1.0 or TLS 1.1 connections to AWS APIs from your account that must be updated for you to maintain AWS connectivity. Please update your client software as soon as possible to use TLS 1.2 or higher to avoid an availability impact. We recommend considering the time needed to verify your changes in a staging environment before introducing them into production... Now AWS has only provided me ip address (which is my server's IP), message Id, and tls version. I have multiple projects running on that server and using the same SES to send mails. Region | Event | Message ID | Source IP | TLS Version <region-of-my-aws-account> | SMTP Message | <smtp-message-id> | <ip-address> | TLSv1 | Im still unsure which ones are using which TLS version. I want to pinpoint my project which is using TLS 1.1/1.0 Is there a way maybe I can print TLS version along in my log files while sending mail? my settings are as follows: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = '<AWS SMTP endpoint>' EMAIL_HOST_USER = os.getenv('AWS_SES_SMTP_USERNAME') EMAIL_HOST_PASSWORD = os.getenv('AWS_SES_SMTP_PASSWORD') EMAIL_USE_TLS = … -
Language selection navbar
Below is my code that works pretty fine and it changes the language of my website, but I want the navbar to change the link 'language' to 'russian' or 'spanish' and etc everytime the user chooses the language. I mean if the user chooses english, in navbar there should be 'english', not just 'language'. <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false"> Languages </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdown"> {% get_current_language as LANGUAGE_CODE %} {% get_available_languages as LANGUAGES %} {% get_language_info_list for LANGUAGES as languages %} {% for lang in languages %} <li> <a class="dropdown-item" href="/{{ lang.code }}/"> {{ lang.name_local }} </a> </li> {% endfor %} </ul> </li> -
Passing kwargs from Resource to widget
I've been working with django import_export and I wanted to pass kwargs from the resource to the clean field of my custom widget validator. how can i do that here's my code resources.py class UserResource(ModelResource): identifier = Field( column_name="identifier", attribute="identifier", widget=RegexWidget(), ) class Meta: model=User widgets.py class RegexWidget(CharWidget): def clean(self, value, row=None, **kwargs): regex = kwargs.get("regex", None) ... In the test I've tries something like the following UserResource.import_data(dataset, regex=r"U\{4}d\Z") but the kwargs from the clean method of the widget is {}