Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
call function of views.py from django template (onclick)
I want to call method "SendOTP" which is written in views.py from django template onclick. I just want to call function , i don't want any change template or url. Other user input form value must be remain after calling function <form method="POST"> {% csrf_token %} {% bootstrap_form form %} <input type="number" name='mobile' placeholder="mobile"> <input type="button" class='btn btn-primary' onclick="SendOTP()" value="Get otp"></input> <button type="submit" class='btn btn-primary' disabled>Sign Up</button> </form> -
Django, send_mail, gets not enough values to unpack
ValueError at /accounts/password_reset/ not enough values to unpack (expected 2, got 1) Request Method: POST Request URL: http://127.0.0.1:8000/accounts/password_reset/ Django Version: 3.1 Exception Type: ValueError Exception Value: not enough values to unpack (expected 2, got 1) Exception Location: d:\Python\Code\dictionary.env\lib\site-packages\django\core\mail\message.py, line 96, in sanitize_address Python Executable: d:\Python\Code\dictionary.env\Scripts\python.exe Python Version: 3.9.1 class CustomResetPasswordView(PasswordResetView): def post(self, request, *args, **kwargs): email = request.POST.get('email') try: _user = User.objects.filter(email=email).first() if not _user: raise Exception('Invalid email address!') else: context = { 'email' : _user.email, 'domain' : get_current_site(request).domain, 'uid' : urlsafe_base64_encode(force_bytes(_user.pk)), 'user' : _user, 'token' : default_token_generator.make_token(_user), 'protocol': 'https' if request.is_secure() else 'http', } _superuser = User.objects.filter(is_superuser=True).values_list('email').first() send_mail( subject='Password Reset Request', message=context, from_email=_superuser, recipient_list=[_user.email] ) except Exception as e: raise settings: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_USE_TLS = True EMAIL_HOST = 'mail.smtp2go.com' EMAIL_HOST_USER = 'confidential' EMAIL_HOST_PASSWORD = 'confidential' -
Connecting a custom logger written using the pythonjsonlogger
I wrote the following logger. How can I connect it to Django for different levels? import inspect import logging from datetime import datetime from pythonjsonlogger import jsonlogger class Logger: def __init__(self, name: str): self.logger = logging.getLogger(name) self.logger.setLevel(logging.INFO) console = logging.StreamHandler() log = logging.FileHandler(filename="logs.log") formatter = jsonlogger.JsonFormatter() log.setFormatter(formatter) log.setLevel(logging.INFO) console.setLevel(logging.ERROR) if self.logger.hasHandlers(): self.logger.handlers.clear() self.logger.addHandler(log) self.logger.addHandler(console) def get_log_data(self): curframe = inspect.currentframe() self.calframe = inspect.getouterframes(curframe, 2) previous_frame = curframe.f_back self.lines = inspect.getframeinfo(previous_frame)[3] self.class_name = previous_frame.f_locals["self"].__class__.__name__ time = datetime.now() self.log_time = time.strftime("%a, %d %b %Y %H:%M:%S%z") def log_error(self, message: str, traceback: str, parent_id: str): self.get_log_data() self.logger.error( message, extra={ "datetime": self.log_time, "level": "ERROR", "class_name": self.class_name, "fnc_name": self.calframe[1][3], "parent_id": parent_id, "stack": traceback, "fnc_call": " -> ".join(self.lines), }, ) def log_info(self, message: str, parent_id: str = None): self.get_log_data() self.logger.info( message, extra={ "datetime": self.log_time, "level": "INFO", "class_name": self.class_name, "fnc_name": self.calframe[1][3], "fnc_call": " -> ".join(self.lines), "parent_id": parent_id, }, ) -
BootstrapError Form
I'm getting this error in my template: Exception Value: Parameter "form" should contain a valid Django Form. My forms.py: from django import forms from .models import CostumerProfile class CostumerForm(forms.ModelForm): class Meta: model = CostumerProfile fields = ('name', 'email', 'phone', 'business') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'email': forms.EmailInput(attrs={'class': 'form-control'}), 'phone': forms.TextInput(attrs={'class': 'form-control'}), 'business': forms.Select(attrs={'class': 'form-control'}), } In my views.py I did this: from django.http.response import HttpResponseRedirect from django.urls import reverse from django.shortcuts import render from .forms import CostumerForm def index(request): return render(request, 'landingpage/index.html') def about(request): return render(request, 'landingpage/about.html') def new_contact(request): if request.method == 'POST': form = CostumerForm(request.POST) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('landingpage:thanks')) else: form = CostumerForm() return render(request, 'landingpage/index.html', {'form': form}) def thanks(request): return render(request, 'landingpage/thanks.html') My index.html form section: <!-- Contact Section--> <section class="page-section" id="contact"> <div class="container"> <!-- Contact Section Heading--> <h2 class="page-section-heading text-center text-uppercase text-secondary mb-0">Contact Me</h2> <!-- Icon Divider--> <div class="divider-custom"> <div class="divider-custom-line"></div> <div class="divider-custom-icon"><i class="fas fa-star"></i></div> <div class="divider-custom-line"></div> </div> <!-- Contact Section Form--> <div class="form-floating mb-3"> <div class="row justify-content-center"> <div class="col-lg-8 col-xl-7"> <form action="{% url 'landingpage:index' %}" method="post" class="form"> {% csrf_token %} {% bootstrap_form form %} {% buttons %} <button class="btn btn-primary btn-xl enabled" id="submitButton" type="submit">Send</button> {% endbuttons %} </form> </div> </div> </div> </div> </section> Any … -
Django Admin LTE WebApp: How do I fix random decimal separators in firefox browser, while chrome works perfectly?
I have the problem that the separators of decimal numbers on my Python Django website in Chrome work wonderfully and are consistent. When I open the website with Firefox, the separators change from "," to "." in completely random places. chrome view firefox view As far as I know, the problem only occurs in Firefox. Any tips would be appreciated! models.py class PVSystem(Component): capacity = models.FloatField(null=True) efficiency = models.FloatField(null=True) spec_opex = models.FloatField(null=True) feed_in_tariff = models.FloatField(null=True) forms.py: class PVSystemForm(ModelForm): prefix = 'PV' total_capex = FloatField(label=_('Preis'), widget=NumberInput(attrs={'min': '0', 'class': 'form-control'})) total_opex = FloatField(label=_('Betriebskosten'), widget=NumberInput(attrs={'min': '0', 'class': 'form-control'})) area = FloatField(label=_('Fläche'), widget=NumberInput(attrs={'min': '0', 'class': 'form-control'})) -
How do I read a request.FILES into DataSource in Geodjango
So, the goal is to create a webpage to load a .shp file into and get a summary of some calculations as a JsonResponse. I have prepared the calculations and everything and it works nicely when I add a manual path to the file in question. However, the goal is for someone else to be able to upload the data and get back the response so I can't hardcode my path. The overall approach: Read in a through forms.FileField() and request.FILES['file_name']. After this, I need to transfer this request.FILES object to DataSource in order to read it in. I would rather not upload the file on pc if possible but work directly from the memory. forms.py from django import forms from django.core.files.storage import FileSystemStorage class UploadFileForm(forms.Form): # title = forms.CharField(max_length=50) file = forms.FileField() views.py import json import os from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render from django.template import loader from django.contrib import messages from django.views.generic import TemplateView from django.http import JsonResponse from django.conf import settings from .forms import UploadFileForm from . import models from django.shortcuts import redirect from gisapp.functions.functions import handle_uploaded_file, handle_uploaded_file_two from django.contrib.gis.gdal import DataSource from django.core.files.uploadedfile import UploadedFile, TemporaryUploadedFile import geopandas as gpd import fiona … -
How to Implement multiple kinds of users in Django?
I am new to Django so please bear with me if my questions seem too basic. So, I want to create a web app for a kind of a store in which I have three different kinds of users. Admin(Not Superuser) who can: create, view, update, delete account for a Seller(agent) issue them inventory Seller who can: sell an inventory item to a Customer(customers cannot themselves purchase it, only the seller can do it by filling in a form) a Customer account should automatically be created upon submission of the form by Seller or if the Customer already has an account, the purchase should be added to their account Customer can login and view their account What would be the best way to go about it? Using auth Groups, Profile models or anything else? Any help would be wonderful. If something is not very clear in the question, I can provide more details. Thanks. -
Getting 404 error continuously after starting Django
I have just started to learn Django framework version 3.2.4 I did some online lessons for last two days but suddenly started getting 404 error. Reverted many things from settings.py and urls.py but no luck. Not Found: /__original-stack-frame Not Found: /__original-stack-frame [01/Jul/2021 00:25:13] "GET /__original-stack-frame?moduleId=undefined&lineNumber=undefined&columnNumber=undefined HTTP/1.1" 404 12101 [01/Jul/2021 00:25:13] "GET /__original-stack-frame?moduleId=undefined&lineNumber=undefined&columnNumber=undefined HTTP/1.1" 404 12101 Above loops continuously and I am not able to figure out the issue. My urls.py contains urlpatterns = [ path('admin/', admin.site.urls), path('playground/', include('playground.urls')), path('__debug__/', include(debug_toolbar.urls)), ] And settings.py contains INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', # 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'debug_toolbar', 'playground' ] Can someone help? -
How to append a link button to a django admin view
How do I add a custom button in an Import view of the Django Admin? We need to include a template file so that users can upload data easily. I don't know if it can be done from the class or if it has to be included somewhere else. I couldn't find this view, apparently it's automatically generated by the admin. -
How do I update a variable set by 'with' in Django Template
Following is the code where I need to update a variable. {% with a=1 %} {% for x in object_list %} {% if 'clone' in x.game and a is 1 %} <div class="alert alert-primary"> <h2 class="p-3">{{ x.title }}</h2> </div> {{ a=2 }} {% endif %} {% endfor %} {% endwith %} {{ a=2 }} does not set a to 2, throws the following error TemplateSyntaxError at / Could not parse the remainder: '=2' from 'a=2' -
Customize PasswordResetConfirmView
I'm trying to set a user is_active state to True when the user have clicked on the reset-password link I've emailed them. However, I don't understand how to get access to the PasswordResetConfirmView, the code below don't do any prints when I go to the related URL. Any ideas on how I should do this? from django.contrib.auth import views as auth_views class PasswordResetConfirmView(auth_views.PasswordResetConfirmView): print("Request view") def get(self, request, *args, **kwargs): print(request) print(request.user) return super().get(request, *args, **kwargs) -
How to set a ManyToMany field to an existing object in a Django migration?
I'm trying to migrate a 1-to-many field to an existing many-to-many field. I'll explain. If I understood what was happening exactly, this question would be shorter. However, I'll try to give all the detail in hopes someone will spot the issue. For migrating a 1-to-many to a new many-to-many, I read this blog post (also like this question), which worked. To summarize: They started with a 1-to-many model (pizza has one topping): from django.db import models class Topping(models.Model): name = models.CharField(max_length=20) class Pizza(models.Model): name = models.CharField(max_length=20) topping = models.ForeignKey(Topping) and showed the migrations to get from one topping to multiple toppings per pizza. In the second of three migrations they add a topping to the new many-to-many toppings field in a forward method of a migration which looks like this: def forward(apps, schema_editor): Pizza = apps.get_model("pizza", "Pizza") for pizza in Pizza.objects.all(): pizza.toppings.add(pizza.topping) However, now I'm trying to migrate a different model to use the existing toppings. add isn't right, because I don't want to create new relationships, I want to use existing ones. This is stretching the pizza example, but suppose I have a note for some pizzas about their topping (I dunno, calories?). That worked when there was one … -
React Socket.io Store Messages
I made simple chat app with Socket.io (tutorial - github) I made a users model on Django and integrated with this app. But when i close the browser and login user account again, messages be lost. I want to store messages. How can i handle with this? -
How to implement OTP based verification before letting the user to create a new password using pyotp?
I am very new to Django rest framework. I am building APIs for my mobile application. In Forgot password module, I have the below flow 1 - Ask user to enter mobile 2 - check existence 3 - If exists - > send OTP 4 - Verify and let user create a new password. But in this case, I would like to know the way of handle the below situation. When one user requests otp and waiting for it to verify , meanwhile another user requests for OTP At this time, how to handle the both user ? I thought of 1 - creating the dictionary and save the user id as key and otp as value in views.py to verify particular user . 2 - store the otp temporarily until it verifies. Kindly let me know which is the secured way and any alternative for this kind of scenario -
DJango deployment on Apache24 not working
I am new to web frameworks and I have designed small website using DJango-3.1.7. I am trying to deploy DJango website on Apache server in Windows 10 platform but it seems something not correct or I missed out it. If anyone could help with this we be precious for me. I have configured virtual environment for this application Problem: Getting error PYTHONHOME = (not set) PYTHONPATH = (not set) error.log Python path configuration: PYTHONHOME = (not set) PYTHONPATH = (not set) program name = 'python' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = 'C:\\Apache24\\bin\\httpd.exe' sys.base_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.base_exec_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.executable = 'C:\\Apache24\\bin\\httpd.exe' sys.prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.exec_prefix = 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38' sys.path = [ 'C:\\Users\\Hp\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', '.\\DLLs', '.\\lib', 'C:\\Apache24\\bin', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00002838 (most recent call first): <no Python frame> [Sat Jun 26 21:56:47.558067 2021] [mpm_winnt:crit] [pid 5344:tid 780] AH00419: master_main: create child process failed. Exiting. etc/hosts 127.0.0.2 stack-hack.com httpd.conf LoadFile "c:/users/hp/appdata/local/programs/python/python38/python38.dll" LoadModule wsgi_module "e:/Code-Stack/stack-hack/lib/site-packages/mod_wsgi/server/mod_wsgi.cp38-win_amd64.pyd" WSGIPythonHome "e:/Code-Stack/stack-hack" WSGIPythonPath "e:/Code-Stack/stack-hack/Lib/site-packages" <VirtualHost *:80> ServerAlias www.stack-hack.com ServerName stack-hack.com ServerAdmin info@admin.com WSGIScriptAlias / "E:/Code-Stack/Stack-Hack/src/stackhack/wsgi.py" <Directory … -
How to specify dynamic url in django template for class based view using router?
path('api/', include(router.urls), name='api'), path('index/' , home, name='home'), path('about/' , about, name='about'), router.register('bankdetailapi', views.BankViewSet, basename='bankdetail' ) how i wrote urls in template href="{% url 'about' %}" href="{% url 'api' %}" href="{% url 'home' %}" i am getting following error Traceback (most recent call last): File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\rest_api\api\views.py", line 36, in home return render(request,'index.html' #,{"ifsc":ifsc} File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 170, in render return self._render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\loader_tags.py", line 150, in render return compiled_parent._render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 162, in _render return self.nodelist.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 938, in render bit = node.render_annotated(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\base.py", line 905, in render_annotated return self.render(context) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\template\defaulttags.py", line 446, in render url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) File "C:\Users\JAY SARDAR\projects\Django+Angular\Fyle-assignment\Backend\restapi\lib\site-packages\django\urls\base.py", line 86, in … -
django orm sort by foreign key occurence in another table
Suppose to have something like the following tables: class Book(models.Model): title = models.CharField(max_length=200) class Purchase(models.Model): book = models.CharField(Book, db_column="book", on_delete=models.CASCADE) date = models.DateField() and wanting to retrieve a queryset of books ordered by number of purchases (i.e. occurrences of the foreign key in the other table). Book.objects.all().annotate(number_of_purchases=Count(**something**)).order_by('number_of_purchases') Is this possible? I currently have no idea what the "something" should be replaced with. -
Authenticate Public APIs with HMAC and Cloudflare?
I have a react.js website that gets data from my Django-based public API. I'm looking at using HMAC tokens to authenticate my client's requests to my backend API. How do I securely implement HMAC tokens in React that are valid with Cloudflare: https://developers.cloudflare.com/firewall/recipes/require-valid-hmac-token Cloudflare proxies all requests to my backend so I need a way of enforcing the authenticity of my client if possible. -
Using custom models.py module name with custom user account app in Django
I have a custom user account model which I use in the settings like so; AUTH_USER_MODEL = 'user_account.UserAccount' This obviously refers to user_account.models.UserAccount model class. Though, I would like to rename the models.py module to user_account_models.py, in which case django naturally complains about user_account.UserAccount not being exist. I've checked the doc, and models are stated in app.ModelName format, nothing in between to refer to where the model is "since django assumes they will always be in models.py in every app" I assume. Is there a way to make django use custom names for models.py module (or any module for that matter) for a particular app (since every app will have it's own distinctive name with the app name as prefix)? -
On going to the profile page, the 'profile_pic' has no file associated with it, value error shows up
When I log in a new user this error that no files are associated with the 'profile_pic' shows up and i've set the profile_pics value to default as well but i don't know the issue any more this is models.py: from django.db import models from django.contrib.auth.models import User class Profile(models.Model): user = models.OneToOneField(User,null= True , blank = True, on_delete= models.CASCADE) profile_pic = models.ImageField(default = "static/profileimages/msi.jpg", null = True, blank= True) first = models.CharField(max_length=500, null=True) last = models.CharField(max_length=500, null=True) email = models.CharField(max_length=500, null=True) mobile_number = models.IntegerField(null=True) location = models.CharField(max_length= 500, null= True) postal = models.IntegerField(null=True) def __str__(self): return self.first This is the views.py: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from .forms import CreateUserForm, ProfileForm from django.http import HttpResponse, HttpResponseRedirect from django.contrib import messages from django.contrib.auth import login, authenticate, logout from django.contrib.auth.decorators import login_required from .models import * def RegisterPage(request): if request.user.is_authenticated: return redirect('Profile') else: if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): user = form.save() name = form.cleaned_data.get('first_name') messages.success(request, 'Account created for ' + name) Profile.objects.create( user = user, ) return HttpResponseRedirect('/Login/') else: form = CreateUserForm() context = {'form':form} return render(request, 'register.html', context) @login_required(login_url='Login') def profile(request): profile = request.user.profile form = ProfileForm(instance=profile) if request.method == 'POST': form … -
A field already has access to the other foreign key in a table
class User(models.Model): ... class Phone(models.Model): user = models.ForeignKey(User) phone = models.TextField() class profile(models.Model): user = models.ForeignKey(User) user_phone = models.ForeignKey(Phone) Already user field in profile has access to phone, So is this design ok or bad based on a normalization view? -
Django Rest Framework error in nested create serializers
I am trying to insert info into the db with nested serializers, but I have errors dummy models class Supplier(models.Model): name = models.CharField('Nombre', max_length=250) class SupplierContacts(models.Model): supplier = models.ForeignKey( 'Supplier', related_name='contacts', on_delete=models.CASCADE ) last_name = models.CharField(max_length=50) class SupplierUsers(models.Model): supplier = models.ForeignKey( 'Supplier', related_name='users', on_delete=models.CASCADE ) last_name = models.CharField(max_length=50) dummy serializers class SupplierSerializer(serializers.ModelSerializer): users = SupplierUserSerializer() contacts = SupplierContactsSerializer(many=True) class Meta: model = Supplier fields = [ 'name', 'users', 'contacts' ] def create(self, validated_data): users_data = validated_data.pop('users') contacts_data = validated_data.pop('contacts') supplier = Supplier.objects.create(**validated_data) SupplierUsers.objects.create(supplier=supplier, **users_data) for contact in contacts_data: SupplierContacts.objects.create(supplier=supplier, **contact) return supplier In views custom create like this class ViewSet(mixins.CreateModelMixin, viewsets.GenericViewSet): queryset = Supplier.objects.all() serializer_class = SupplierSerializer def create(self, request, *args, **kwargs): # import ipdb # ipdb.set_trace() serializer = SupplierSerializer(data=request.data) if serializer.is_valid(): serializer.save() # here works saved to db return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) I am doing what it says in the documentation, but I have the following error. AttributeError: Got AttributeError when attempting to get a value for field `last_name` on serializer `SupplierUserSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `RelatedManager` instance. Original exception text was: 'RelatedManager' object has no attribute 'last_name'. Data is saved, the problem is in … -
how to test react component without updating the db
this is my test for users registration the problem is that the test actually register the user and update the db. therefore because the user getting created at the second run the test fails (beacuse the user is already registered) I wonder is there a way which I can test this component without updating the db? I am using postgreSQL as my database and django rest as my api. for the front end I am using react and for the testing: react testing library + jest test('signup should dispatch signupAction', async () => { const middlewares = [thunk]; const mockStore = configureStore(middlewares); initialState = { authReducer: { isAuthenticatedData: false }, }; const store = mockStore(initialState); render( <Provider store={store}> <Router> <UserSignup /> </Router> </Provider> ); const nameTextbox = screen.getByPlaceholderText('Name*'); const emailTextbox = screen.getByPlaceholderText('Email*'); const passwordTextbox = screen.getByPlaceholderText('Password*'); const confirmTextbox = screen.getByPlaceholderText('Confirm Password*'); const signupButton = screen.getByRole('button', { name: 'Register' }); userEvent.type(nameTextbox, 'newtestuser'); userEvent.type(emailTextbox, 'newtestuser@gmail.com'); userEvent.type(passwordTextbox, 'testuser123'); userEvent.type(confirmTextbox, 'testuser123'); userEvent.click(signupButton); await waitFor(() => expect(store.getActions()[0].type).toBe('SIGNUP_SUCCESS')); }); user sign up component const userSignup = () => { const dispatch = useDispatch(); const isAuthenticatedData = useSelector((state) => state.authReducer.isAuthenticatedData); const [formData, setFormData] = useState({ name: '', email: '', password: '', re_password: '', }); const [accountCreated, setAccountCreated] … -
TypeError: __str__ returned non-string (type NoneType) - Django
I have an error when trying to make a data listing request: MyModel: import uuid import time from django.db import models from a.models import ModelA from b.models import ModelB def upload_location(instance, filename): filebase, extension = filename.split('.') milliseconds = int(round(time.time() * 1000)) return 'a_id__%s/%s__%s.%s' % (instance.a_id, instance.name, milliseconds, extension) class Attachment(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False, null=False) name = models.CharField(max_length=150) file = models.FileField(upload_to=upload_location) a = models.ForeignKey( ModelA, null=True, blank=False, on_delete=models.CASCADE ) b = models.ForeignKey( ModelB, null=True, blank=False, on_delete=models.CASCADE ) def __str__(self): return self.name Viewset: class AttachmentsViewSet( mixins.ListModelMixin, mixins.CreateModelMixin, mixins.DestroyModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet ): permission_classes = [permissions.AllowAny] queryset = Attachment.objects.all() serializer_class = AttachmentSerializer def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) data = serializer.validated_data data['a_id'] = request.user.a_id data['name'] = str(request.data['file']) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) Serializer: class AttachmentSerializer(ModelSerializer): class Meta: model = Attachment fields = "__all__" class ASerializer(ModelSerializer): attachment = serializers.SerializerMethodField('get_attachment_model_b') class Meta: model = ModelB fields = ( 'id', 'type', 'name', 'status', 'attachment' ) def get_attachment_model_b(self, obj): attachment = Attachment.objects.filter(b_id=obj.b_id).all() return AttachmentSerializer(instance=attachment, many=True).data Error: I've tried the following ways and without success... def __str__(self): return str(self.name) def __str__(self): return self.name or '' def __str__(self): return self.get_full_name This error happens when I try to open the screen to … -
Bulk Create catch exceptions in Django
I'm trying to create 30,000 objects in Django but need the error response for each object. Bulk create with ignore conflicts as True will partially create which is not what I want and ignore conflicts as False will stop at the first error. Is there any efficient way to catch error at each row without hitting database 30,000 times?