Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How can we remove null key : value pair from the Django response?
I'm getting the response as where I don't want to send the null key: value pair to the client How can we remove null key : value pair from the Django response? -
NameError: name 'DATABASES' is not defined Heroku
When I try to deploy a Django app at Heroku, I got this error. NameError: name 'DATABASES' is not defined. I have created Postgres from resources, but sill I don't know why I am getting this error -----> Python app detected ! Python has released a security update! Please consider upgrading to python-3.7.9 Learn More: https://devcenter.heroku.com/articles/python-runtimes -----> No change in requirements detected, installing from cache -----> Installing pip 20.1.1, setuptools 47.1.1 and wheel 0.34.2 -----> Installing SQLite3 -----> Installing requirements with pip -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.7/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.7/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.7/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_a013ae50_/main_app/settings.py", … -
Bootstrap Card Shrinks after Search Button Clicked
I am pretty new to Boostrap, I've mainly been doing backend stuff, but am now doing front end work. I have a feature where the user searches a place and a list of nearby venues pops up. I'd like these to pop up in a card. I am using bootstrap cards. At the moment I have 2 problems: On load there is just this big card sitting there all clumsy: When I execute a search the card snaps down to a tiny scrollable version and all the content divs (map/card) seem to drop down a tad. I can probably figure out the javascript needed to make the card appear only when search occurs but I don't know how to set the card at a standard height after search (and prevent the divs from shifting slightly). What I'd like to achieve is a standard height for the card after search. Here is the for the initial card: <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Places Nearby</h5> <div id="cafes"> <div id="cafe_list"></div> </div> </div> </div> Here is the html for the function that generates the list: <div class="cafe-details d-flex"> <ul> {% for cafe in cafes %} <li> <address> <div> <h6 class="cafe-name" data-id="{{ cafe.id … -
Django Render HTML to PDF
I'm trying to render an html file to pdf however while the pdf functionality is working fine the rendering is working properly, no css. Also it renders the whole page, how can i render specific sections of the html page. I'm using xhtml2pdf. views.py file from io import BytesIO from django.http import HttpResponse from django.template.loader import get_template from django.views import View from xhtml2pdf import pisa def render_to_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render(context_dict) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("utf-8")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None data = { "company": "Name", } #Opens up page as PDF class ViewPDF(View): def get(self, request, *args, **kwargs): pdf = render_to_pdf('listings/listing.html', data) return HttpResponse(pdf, content_type='application/pdf') urls.py file path('pdf_view/', views.ViewPDF.as_view(), name="pdf_view"), html file <section class="p0"> <div class="container"> <div class="row listing_single_row"> <div class="col-sm-6 col-lg-7 col-xl-8"> <div class="single_property_title"> <a href="{{ listing.photo_1.url }}" class="upload_btn popup-img"><span class="flaticon-photo-camera"></span> View Photos</a> </div> </div> <div class="col-sm-6 col-lg-5 col-xl-4"> <div class="single_property_social_share"> <div class="spss style2 mt10 text-right tal-400"> <ul class="mb0"> <li class="list-inline-item"><a href="#"><span class="flaticon-transfer-1"></span></a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-heart"></span></a></li> <li class="list-inline-item"><a href="#"><span class="flaticon-share"></span></a></li> <li class="list-inline-item"><a href="{% url 'pdf_view' %}"><span class="flaticon-printer"></span></a></li> </ul> </div> </div> </div> </div> </div> </section> Thank you! -
Why can't I access my template view when trying to register a user with Django?
I'm trying to implement a login functionality to a small Django project but when I go to the page with signup/signin form I get the 404 error. I am using Django default user model and auth forms. here are the views: def signup(request): if request.user.is_authenticated: return redirect('/') if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: return render(request, 'signup.html', {'form': form}) else: form = UserCreationForm() return render(request, 'signup.html', {'form': form}) def signin(request): if request.user.is_authenticated: return render(request, 'homepage.html') if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('/') else: form = AuthenticationForm(request.POST) return render(request, 'signin.html', {'form': form}) else: form = AuthenticationForm() return render(request, 'signin.html', {'form': form}) def log_out(request): logout(request) return redirect('/') here are the urls for my views: urlpatterns = [ path('', views.PostList.as_view(), name='home'), path('signup/', views.signup, name='register'), path('signin/', views.signin, name='signup'), path('log_out/', views.log_out, name='log_out'), ] -
How to connect django model using foreignkey to a unique object in another model
Please how do I connect a model to a particular object in another model using either onetoonefield or foreignkey. Example class Post(models.Model): title = models.TextField(max_length=100, null=True) caption = models.CharField(max_length=1000) photo = models.ImageField(upload_to ='posts', null=True) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) likes= models.IntegerField(default=0) dislikes= models.IntegerField(default=0) price = models.DecimalField(max_digits=10, decimal_places=2, null=True) digital = models.BooleanField(default=False, null=True, blank=False) location = models.PointField(srid=4326, null=True) category = models.ForeignKey('Category', null=True, blank=True, on_delete=models.CASCADE) slug = models.SlugField(unique=True, null=True) def __str__(self): return self.title @property def number_of_comments(self): return Comment.objects.filter(post_connected=self).count() class Comment(models.Model): **post_owner = models.OneToOneField( )** content = models.TextField(max_length=150) date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) post_connected = models.ForeignKey(Post, on_delete=models.CASCADE) I need to make post_owner in Comment Models, connected to author in Post models and not the entire Post models -
How to set default Field attributes i.e ( max_length) for the whole project - Django
What's the best way to set global default attributes for a model Field in Django ? Say i have many DecimalField() in various models in my app, and i want to set a default max_digits and decimal_places globally so it applies to all my DecimalFields ?? -
How to overwrite default django admin login view
I need to modify default django admin login functionality while keeping the rest untouched. I found the login.html template, but I need to work on some data I receive from modified login template. I see mentions of LoginView, and expected to see something like login method in which all the workflow is done, but see none. -
Django makemigrations return KeyError
So, when I tried makemigrations command I got this error *Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, **kwargs) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 147, in _migrate_all_forwards state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 245, in apply_migration state = migration.apply(state, schema_editor) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 114, in apply operation.state_forwards(self.app_label, project_state) File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 165, in state_forwards for name, instance in state.models[app_label, self.model_name_lower].fields: KeyError: ('Conversation', 'user_pos')Traceback (most recent call last): File "manage.py", line 22, in execute_from_command_line(sys.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 381, in execute_from_command_line utility.execute() File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/init.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 364, in execute output = self.handle(*args, **options) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/base.py", line 83, in wrapped res = handle_func(*args, *kwargs) File "/home/panasonic/.local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 234, in handle fake_initial=fake_initial, File "/home/panasonic/.local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 117, in migrate state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial) … -
Name 'member_one' is not defined error in django
I want to get all Message_thread_private instances from database but I am getting error NameError: name 'member_one' is not defined Models.py: class Message_thread_private(models.Model): member_one = models.ForeignKey(User, related_name='member_one_messages', on_delete=models.CASCADE) member_two = models.ForeignKey(User, related_name='member_two_messages', on_delete=models.CASCADE) content = models.TextField() created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.member_one.username def last_10_messages(): return Message.objects.order_by('-timestamp').all()[:10] views.py: @login_required def room(request, room_name): users = User.objects.filter(is_active=True).exclude(username=request.user.username) messages = Message_thread_private.objects.filter(member_one.username==request.user.username) return render(request, 'chat/room.html', { 'room_name_json': mark_safe(json.dumps(room_name)), 'username': mark_safe(json.dumps(request.user.username)), 'users': users, }) Why am i getting this error and how can I resolve this? -
What is the benefit of learning sql over sqlalchemy?
I was reading this: Using and connecting application through an ORM (Object Relational Mapper) like SQLAlchemy, Django ORM and so on is easier, faster, and more efficient than writing SQL - which means, more likely, it is preferred by the team. Good to have it in your skillset! So, I guess I would work with these platforms easier than the based ones? Can someone explain more smoothly? -
DEADLINE IS NEAR - NOTIFICATION
I'm doing a django-project that manages some projects. Each project has its deadline, and I'd like to implement the fact that when the deadline is in 3 days for example, the system sends a notification to the employee that is working on that project. I haven't decided if the notification should be sent as an email to the worker, or if it should be a notification sent to the worker's profile on my webapp. Could you give me some advice for which is the best way? And in either case how could i do it? Should I use celery or cron-job or something else? -
Celery identify list of worker running on multiple instance
I have celery set up on four different servers. Scheduling task Task #1, Task #2, Task #3 (Each task 10 worker) Task #1, Task #2, Task #3 (Each task 10 worker) Task #1, Task #2, Task #3 (Each task 10 worker) The first server is scheduling a task and the other three servers are executing a task. The setup is quite ok and working flowless. Now I came across one scenario that. Sometimes I need to stop any of the server 2 or 3 or 4. So I want to raise a shutdown broadcast signal for thee of the workers running on a particular server from the first scheduling server. How can I send a shutdown signal to a perticular server's worker? [Django celery, Redis queue] -
How can we use python for loop variable for the django class field?
I am sending ajax data to the below view I want to save it in the model I have created (mentioned below). Problem is, in that model I want 26 fields as the months so I created that by the add_to_class inside for loop. I don't know how much months user will input so I have to loop the list in views and save the data as: a = '100000' b = '120000' c = '15000' where a, b, c are the months and the rest values will be 0 default. Here is the model ''' class sold(models.Model): car = models.ForeignKey(Car, on_delete=models.CASCADE) Buyer = models.ForeignKey(buyer, on_delete=models.CASCADE) total = models.IntegerField() deposit = models.IntegerField() balance = models.IntegerField() months = models.IntegerField(default=12) tracker = models.IntegerField() insurance = models.IntegerField() def __str__(self): return f'{self.car} {self.Buyer} {self.total} {self.balance} for i in ascii_lowercase: sold.add_to_class('%s'%i, models.CharField(default=0, max_length=255,null=True, blank=True))''' NOTE: I have tried range(1, 27) with str and int but it didn't worked out. The views.py def sale_car_data(request): if request.method == 'POST': check = request.POST['car'] # if soldTo.objects.filter(car__chasis=check).exists(): # return HttpResponse('Already Exist') if 1==1: #Some condition here insurance = request.POST['insurance'] month = request.POST['month'] installment = request.POST.getlist('installment') installment = [json.loads(item) for item in installment] sale = sold(car=pro, Buyer=buyer, total=total, deposit=deposit, balance=balance, … -
registration and login form without use django authentications
I have a registration and login form but I dont want to use django authentications. I want to log in using the username and password that the user enters in the registrationform. How can I say that the content of the field inside the template is equal to the fields of my model.Im begginer in django and i hope help me. model.py class Customer (models.Model): CustomerUserName=models.CharField(unique=True,max_length=150) CustomerFirstName=models.CharField( max_length=150) CustomerLastName=models.CharField(max_length=150) CustomerPassWord=models.CharField(max_length=150) CustomerSerialNum=models.CharField(max_length=10) CustomerPhonNum=models.CharField(max_length=11) CustomerAddress=models.TextField(max_length=1000) CustomerEmail=models. EmailField(max_length=256) GENDER=( ('a','male'), ('b','female'), ) CustomerGender=models.CharField(max_length=1,choices=GENDER) CustomerBirthDate=models.DateField(null=True,blank=True) CustomerImage=models.ImageField(upload_to ='upload/userimage/' ) def __str__(self): return '%s %s' % (self.CustomerFirstName, self.CustomerLastName) return self.CustomerUserName.username form.py class SignUpForm(forms.ModelForm): CustomerFirstName = forms.CharField(max_length=150,label='firstname') CustomerLastName = forms.CharField(max_length=150,label=' lastname ') CustomerEmail = forms.EmailField(max_length=256,label=' Email',widget=forms.TextInput( attrs={ 'placeholder': 'example@gmail.com'} )) CustomerPhonNum = forms.CharField(max_length=150,label=' phone number',widget=forms.TextInput( attrs={'class':'phone' ,'placeholder': '09xxxxxxxxx'} )) CustomerPassWord = forms.CharField( label=' password ', widget=forms.PasswordInput( attrs={'class':'psw', 'pattern':'(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' } )) class Meta: model = Customer fields = ['CustomerUserName','CustomerFirstName', 'CustomerLastName','CustomerEmail','CustomerPhonNum','CustomerPassWord'] class SignInForm(forms.ModelForm): CustomerPassWord = forms.CharField( label=' password', widget=forms.PasswordInput( attrs={'class':'psw', 'pattern':'(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,}' } )) class Meta: model = Customer fields = ['CustomerUserName','CustomerPassWord'] view.py def signin(request): form=SignInForm() if request.method== 'POST': form=SignInForm(data=request.POST) if form.is_valid(): UserName = form.cleaned_data['CustomerUserName'] PassWord = form.cleaned_data['CustomerPassWord'] return render(request,'index.html',{'form': form}) else: return HttpResponse('this user is not exist') else: form=SignInForm() return render(request,'signin.html',{'form': form}) def signup(request): form = SignUpForm() if request.method=='POST': … -
Run a celery task every 90 mins from 1:30am-6am UTC
Can we make a celery task run at 1:30, 3:00, 4:30, 6 AM using single crontab function? i.e 'schedule': crontab(minute=30, hour='1, 3, 4, 6') will run it at 1:30, 3:30, 4:30, 6:30AM but I want it to run every 90 mins from 1:30 to 6AM -
How to define multiple serializers in a django mixin?
I'm currently writing views to display my objects. But in those views, I want to have some query parameters to filter my objects. I'm using drf-yasg to generate the schema and django-rest-framework for the views. So for example I have this serializer for the filter data: class IceCreamFilterSerializer(serializers.Serializer): start = serializers.DateField() and I have this view: @method_decorator(name='list', decorator=swagger_auto_schema( manual_parameters=[openapi.Parameter('start', openapi.IN_QUERY, type=openapi.TYPE_STRING)] )) class IceCream(ListModelMixin, GenericViewSet): serializer_class = IceCreamSerializer def get_queryset(self): filter_data = IceCreamFilterSerializer(data=self.request.query_params) start = filter_data['start'] qs = IceCream.objects.filter(created__gte=start) return qs This works okay, but then I want to implement this method to my other views. So I want to create a Mixin so that I can inherit the Mixin in the view classes. But the problem is, how do I define the input and output serializer in the Mixin? Do I have to override get_serializer_class there? Note: I know I can use FilterSet from DRF to filter, but I feel like this method is the better way for my case. Any help would be really appreciated. Thanks in advance! -
Altering the fields of User custom model in Django
I have already built in backend like this. Now I have to make api for user registration. For that I need to remove 'name' field from class User(AbstractBaseUser, PermissionsMixin): and add with first_name and last_name instead. Can I have the privilige of doing that directly?? Because when I try that, mySQL data base is showing error that cant drop the perivious field of 'name'. What is the issue?? class UserManager(BaseUserManager): def create_user(self, email, password=None, **kwargs): """Creating new user and saving the user.""" if not email: raise ValueError('Admin must have a valid email') user = self.model(email=self.normalize_email(email), **kwargs) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, password): """Creates and saves a new super user""" user = self.create_user(email, password) user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class User(AbstractBaseUser, PermissionsMixin): """ Custom user model that supports using email instead of username """ email = models.EmailField(max_length=255, unique=True) name = models.CharField(max_length=255) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=True) object = UserManager() USERNAME_FIELD = 'email' -
Adding a class attribute to a queryset field on ModelForm
So I'm trying to add a class attribute to this field on my ModelForm to allow for Bootstrap styling: category = forms.ModelChoiceField(queryset=Category.objects.all()) I tried this: category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.ModelChoiceField(attrs={'class':'form-control'})) and got this error: TypeError: __init__() missing 1 required positional argument: 'queryset' My complete ModelForm: class NewListingForm(forms.ModelForm): class Meta: model = Listing fields = ["title", "description", "start_price", "image", "category"] title = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'})) description = forms.CharField(widget=forms.TextInput(attrs={'autocomplete':'off', 'class':'form-control'})) start_price = forms.DecimalField(label='Starting Bid Price (£)', widget=forms.NumberInput(attrs={'class':'form-control'})) image = forms.URLField(widget=forms.URLInput(attrs={'autocomplete':'off', 'class':'form-control'})) category = forms.ModelChoiceField(queryset=Category.objects.all(), widget=forms.ModelChoiceField(attrs={'class':'form-control'})) (I was going to do the fields = [] labels={} widgets={} format but I couldn't work out how to do that with a queryset field) -
How to add new values to Many2Many field Django
I'm currently working on a small Django project and I'm having an issue setting a many2many field's value. in my models I have something like : class Operation(models.Model): day = models.DateField() realized_by = models.ManyToManyField(User, related_name="consumer", blank = True) ... in my views.py I want to check: if there is an Operation instance that happened today, then add request.user to the relized_by users list else, create an Operation instance and make request.user the first element of realized_by users list Thank you for your answers in advance. -
Why am I getting a NOT NULL constraint failed when submitting my django form?
I am trying to add comments to my post model in django but when I try to submit a form it throws a NOT NULL constraint failed error because it cannot find a post even though it is being assigned in the view when saving the form. here are my models: class Post(models.Model): title = models.TextField('Title', max_length=300) slug = models.SlugField('Link') created_on = models.DateTimeField('Creation date', auto_now_add=True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') content = models.TextField('Content', max_length=2000, default='!') class Meta: ordering = ['-created_on'] def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments') user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='comment_author') body = models.TextField() created_on = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-created_on'] def __str__(self): return 'Comment {} by {}'.format(self.body, self.user) then this is my form: class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ['user', 'body'] if I add the 'post' field to fields it displays it as a dropdown and adds the comment to the correct post even if the dropdown option points it to a different one but I don't want it to display the 'post' field in the form at all and this is the view: def post_detail(request, slug): template_name = 'post_detail.html' post = get_object_or_404(Post, slug=slug) comments = post.comments.all() new_comment = None … -
How to get Django model id in views.py
I know Django automatically create a unique id for every model created. For example like this fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=100)), ('email', models.EmailField(max_length=50)), ('language', models.CharField(choices=[('ur-PK', 'Urdu'), ('en-US', 'English')], max_length=15)), ], But I want to get this id in views.py file. How can I do this? I am using django model forms to enter data -
Unit tests for OrderingFilter DRF
I have a model: class Trade(models.Model): name = models.CharField(max_length=255, unique=True) is_active = models.BooleanField('Active', default=True) is_deleted = models.BooleanField('Deleted', default=False) and views.py class TradeViewSet(viewsets.ModelViewSet): queryset = Trade.objects.all() permission_classes = [permissions.IsAuthenticated] serializer_class = TradeSerializer filter_backends = [ DjangoFilterBackend, CaseInsensitiveOrderingFilter, SearchFilter ] filter CaseInsensitiveOrderingFilter class CaseInsensitiveOrderingFilter(OrderingFilter): """ Custom filter to order case insensitive fields as CharField and TextField. To define filter it's needed to add char or text fields to list: ordering_case_insensitive_fields = ["field"] """ def filter_queryset(self, request, queryset, view): ordering = self.get_ordering(request, queryset, view) insensitive_ordering = getattr(view, 'ordering_case_insensitive_fields', ()) if ordering: new_ordering = [] for field in ordering: if field.lstrip('-') in insensitive_ordering: if field.startswith('-'): new_ordering.append(Lower(field[1:]).desc()) else: new_ordering.append(Lower(field).asc()) else: new_ordering.append(field) return queryset.order_by(*new_ordering) return queryset And simple serializer class TradeSerializer(serializers.ModelSerializer): class Meta: model = models.Trade fields = ( 'id', 'name', 'is_active', 'is_deleted', ) read_only_fields = ('is_deleted', 'id') my tests.py class TradeAPITest(BaseAPITestCaseSetup): data = { 'name': 'Trade Name 012000', 'is_active': True, } def setUp(self): super().setUp() self.trade = Trade.objects.create(**self.data) factories.TradeFactory.create_batch(10) self.test_data = { 'name': 'Trade Name 2', 'is_active': True, } def test_ordering_by_name_ascending(self): url = reverse('trades-list') + '?ordering=name' response = self.client.get(url) response_results = response.json().get('results') expected_result = sorted(response_results, key=lambda i: i['name'].lower()) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertEqual(response_results, expected_result) def test_ordering_by_name_descending(self): url = reverse('trades-list') + '?ordering=-name' response = self.client.get(url) response_results = response.json().get('results') expected_result … -
Django - Email confirmation - recommendation on what service to use
I want to configure email responses for my Django app (registration, password reset, email confirmation etc) I did filled setting.py with my gmail account credentials while developing, but I don't want get banned if I will use this email after app deployment on server. May you please recommend any service that offers email address for automatic letters? EMAIL_HOST_USER = '' EMAIL_HOST = '' EMAIL_PORT = EMAIL_USE_TLS = True EMAIL_HOST_PASSWORD = '' -
Django don't refresh site when form is invalid
I am currently developing a website for which I use a lot of modals with forms in them. The thing is, every time I enter invalid information in a form field and press the submit button, the modal just closes and there is no indication that the form was invalid. I already know that there is the possibility of making an ajax request which sends the form data to another view which then responds with a JSONResponse that contains errors which can then be displayed. That would work but by doing that I would lose all benefits of django forms. Because I have to submit the form data as JSON, I cant use functions like form.is_valid. So my question is: Is there a way to not refresh the site when a invalid form is submitted and displaying errors without having to send the data via JSON?