Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ModuleNotFoundError: No module named 'photo_app.wsgi'
I'm trying to deploy my Django application using Gunicorn and systemd on an Ubuntu server. However, the Gunicorn service fails to start with the following error. **ModuleNotFoundError: No module named 'photo_app.wsgi' ** ModuleNotFoundError: No module named '*.wsgi'.](https://i.sstatic.net/yNykpB0w.png) In my folder the passport_photo_maker module exists and contains a wsgi.py file. #gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=gopikumarkaushik9065 Group=www-data WorkingDirectory=/home/gopikumarkaushik9065/Passport-Size-Photo-Maker ExecStart=/home/gopikumarkaushik9065/Passport-Size-Photo-Maker/venv/bin/gunicorn --workers 3 --bind unix:/home/gopikumarkaushik9065/Passport-Size-Photo-Maker/gunicorn.sock passport_photo_maker.wsgi:application [Install] WantedBy=multi-user.target if there is no mention of photo_app.wsgi in gunicorn.service then why error is occuring? -
Trying to redirect user from a booking page in django
This is my first Django project and I am really struggling. It is a simple booking app where the logged in user is on a page with a form to make a booking and a list of current bookings. I can make the page work and make a booking but the info in the form isnt cleared and if the page is refreshed it makes the booking again. To solve this, I think I need the page to redirect to a success page after the booking is made. When I try to do this, I get a "NoReverseMatch" error and am told that it is "not a valid view function or pattern name." Here are the url patterns of booking.urls.py: from django.urls import path from . import views urlpatterns = [ path("", views.home, name='home'), path("booking/", views.booking, name='booking'), path('my_bookings/', views.my_bookings, name='my_bookings'), path('edit_booking/<int:booking_id>', views.edit_booking, name='edit_booking'), path('delete_booking/<int:booking_id>', views.delete_booking, name='delete_booking'), path('success_booking/', views.success_booking, name='success_booking'), ] Here are some parts of the booking.views.py: def my_bookings(request): bookings = Booking.objects.filter(user=request.user) booking_form = BookingForm() if request.method == "POST": booking_form = BookingForm(data=request.POST) if booking_form.is_valid(): booking = booking_form.save(commit=False) booking.user = request.user booking.save() return HttpResponseRedirect(reverse('/booking_delete/')) return render( request, "booking/booking_list.html", { 'booking_form' : booking_form, 'bookings': bookings, }, ) And here is the snippet … -
How to convert a web application built in django framework into desktop stand-alone application
I have a django based web application which is working fine. Recently one customer asked for the offline version of the application. Offline means simple stand-alone desktop application. Can we convert or existing Django application into desktop application or do i need to develop the application from scratch using some other framework. There is one solution to the problem is to deploy the application locally on the desktop. But in that case our source code will be available to the customer. Please help me to find out the solution of this problem. Thanks & Regards -
How do I add a prefetch (or similar) to a django queryset, using contents of a JSONField?
Background I have a complex analytics application using conventional relational setup where different entities are updated using a CRUD model. However, our system is quite event driven, and it's becoming a real misery to manage history, and apply data migrations respecting that history. So we're moving toward a quasi-noSQL approach in which I'm using JSON to represent data with a linked list of patches representing the history. As far as data structure goes it's a very elegant solution and will work well with other services. As far as django goes, I'm now struggling to use the ORM. My database is PostgreSQL. Situation Previously I had something like (pseudocode): class Environment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Analysis(models.Model): created = models.DateTime(auto_now_add=True) environment = models.ForeignKey( "myapp.Environment", blank=True, null=True, related_name="analyses", ) everything_else = models.JSONField() Whereas I now will have: class Environment(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) class Analysis(models.Model): created = models.DateTime(auto_now_add=True) everything = models.JSONField() Where everything might be a JSON object looking like... { "environment": "2bf94e55-7b47-41ad-b81a-6cce59762160", "other_stuff": "lots of stuff" } Now, I can still totally get the Environment for a given Analysis because I have its ID, but if I do something like this (again pseudocode): for analysis in Analysis.objects.filter(created=today).all(): print(Environment.objects.get(id=analysis.everything['environment']) I … -
Efficiently query django Query
We are working on newspaper with django. Before read further Let me show you the code. # Fetch lead, top, and other filtered news news_objects = news.objects.filter(website=host, is_published__in=[True], published_date__lt=current_datetime).only('Category','title','news_brief','image','img_caption','published_date','news_id') lead = news_objects.filter(status='lead').order_by('-published_date').first() top = news_objects.filter(status='top').order_by('-published_date')[:4] filtered_news = news_objects.exclude(status__in=['lead', 'top']).order_by('-published_date') # Fetch filtered categories and prefetch limited news related to filtered categories categories_with_news = catagory.objects.filter(website=host, show_front__in=[True]).prefetch_related( Prefetch('catagory', queryset=filtered_news, to_attr='limited_news') ) # Limit the news to the first 5 for each category for category in categories_with_news: category.limited_news = category.limited_news[:6]` Below code will fetch all news in specific domain. News contains more then 10k news_objects = news.objects.filter(website=host, is_published__in=[True], published_date__lt=current_datetime).only('Category','title','news_brief','image','img_caption','published_date','news_id') Below code will get only 5 news from news_objects lead = news_objects.filter(status='lead').order_by('-published_date').first() top = news_objects.filter(status='top').order_by('-published_date')[:4] below code will get all the category which will display in front along with their data. categories_with_news = catagory.objects.filter(website=host, show_front__in=[True]).prefetch_related( Prefetch('catagory', queryset=filtered_news, to_attr='limited_news') ) Again below code will fetch 6 news per category. for category in categories_with_news: category.limited_news = category.limited_news[:6] Here my problem is I don't think so this is good idea to fetch all the news for cause I will need not more then 60 news. How to do it efficiently. I tried limiting the query to 300 but there also a problem may be in some category … -
Python Set Context precision for Decimal field
from decimal import Decimal, setcontext, getcontext class MyNewSerializer(serializers.Serializer): total_value_base = serializers.SerializerMethodField() total_outgoing_value_base = serializers.DecimalField( max_digits=38, decimal_places=8, source="value_sent", ) total_incoming_value = serializers.DecimalField( max_digits=38, decimal_places=4, source="value_received", ) def get_total_value_base(self, obj): total = Decimal(obj.value_received) + Decimal( obj.value_sent ) # Values of above objects # obj.value_received = 425933085766969760747388.45622168 # obj.value_sent = 0 # total = 425933085766969760747388.4562 dec = Decimal(str(total)) return round(dec, 8) But this is throwing error: return round(dec, 8) decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>] This get's fixed when i do the following: def get_total_value_base(self, obj): # the below line fixes the issue getcontext().prec = 100 total = Decimal(obj.value_received) + Decimal( obj.value_sent ) # Values of above objects # obj.value_received = 425933085766969760747388.45622168 # obj.value_sent = 0 # total = 425933085766969760747388.4562 dec = Decimal(str(total)) return round(dec, 8) I want to increase precision for all the values in the class as well as other similar classes. How can i do that using a base class or overriding the Decimal class for the whole file or for various classes in the file? I am expecting to increase the decimal precision for 100's of variables that are present in a file in various different classes. -
Upload multiple photos for a product in the store
I am loading a store site with Django. I need to upload 4 photos for one product But I can only upload one photo can you help me? my models in products: class Product(models.Model): Name = models.CharField(max_length=60) Descriptions = models.TextField() Price = models.IntegerField() Image = models.ImageField(upload_to='product') category = models.ManyToManyField(Category, null=True, blank=True) Discount = models.SmallIntegerField(null=True, blank=True) Size = models.ManyToManyField(ProductSize, related_name='product') Color = models.ManyToManyField(ProductColor, related_name='product', blank=True) Property = models.ManyToManyField(ProductProperty, related_name='product') My Views in products: class ProductDetail(DetailView): template_name = 'product/single-product.html' model = Product -
Django Form Processing - how to create a record and add it as ForeignKey
I would like to solve a problem in form handling my views.py. I would like to process a ModelForm. Instead of letting the user fill the field Field fk_transaction I would like to create a new Record of Transaction and add it as a ForeignKey in the background to the CcountBooking. The Form is displayed correctly in the the template. Also a Transaction is successfully created. However when I want to add and save it to the form in views.py it throws an error telling me that the field is not existing. Thanks for any help! My views.py: from django.http import HttpResponse from django.shortcuts import render from forms import AccountBookingForm from models import Transaction def deposit(request): context = {} if request.method == "POST": form = AccountBookingForm(request.POST) t = Transaction() form.fk_transaction = t form.save() return render(request, "deposit_success.html", {"form": form}) else: form = AccountBookingForm() return render(request, "deposit.html", {"form": form}) My models.py: class Transaction(models.Model): type = models.CharField(max_length=11, choices=TR_TYPE_CHOICES, default=DEPOSIT) status = models.CharField(max_length=11, choices=TR_STATUS_CHOICES, default=DRAFT) text = models.TextField(max_length=500, default="", blank=True) class AccountBooking(models.Model): fk_bankaccount = models.ForeignKey( BankAccount, on_delete=models.CASCADE, blank=False) fk_transaction = models.ForeignKey(Transaction, on_delete=models.CASCADE, blank=False) value = models.DecimalField(max_digits=14, decimal_places=2, blank=False) My forms.py from django.forms import ModelForm from .models import AccountBooking class AccountBookingForm(ModelForm): class Meta: model = … -
How can i add additional Data (ETIM-Featurecodes) to a existing Field [closed]
I have build a model which should representate our Products at work. Our products are different sorts of luminaires. Some of these with different variations like different colour-temperature, different housing-colour, different power, sensors or dimmable. at the moment my model looks (a little shortend) like this class ProductID(models.Model): product_id = models.CharField(max_length=100, unique=True) base_model = models.BooleanField(default=True) active = models.BooleanField(default=True, choices=CHOICES) possible_as_option = models.BooleanField(default=False, choices=CHOICES) product_variant_data = models.ForeignKey('ProductVariantData', on_delete=models.PROTECT) ... class ProductVariantData(models.Model): short_text = models.CharField(max_length=300, null=True, blank=True) packaging_unit = models.IntegerField(validators=[MinValueValidator(1)]) guarantee = models.IntegerField() product = models.ForeignKey('Product', null=True, on_delete=models.PROTECT) ... class Product(models.Model): enec = models.BooleanField(default=False) ce = models.BooleanField(default=True) min_ambient_temperature = models.IntegerField() max_ambient_temperature = models.IntegerField() ip_code = models.ForeignKey(IPCode, on_delete=models.PROTECT) ik_code = models.ForeignKey(IKCode, on_delete=models.PROTECT) dimensions = models.ForeignKey(Dimensions) cutout_dimensions = models.ForeignKey(CutoutDimensions, null=True) product_type = models.ForeignKey(ProductType, on_delete=models.PROTECT) .... class LEDData(models.Model): led_changeable = models.BooleanField(default=True) average_lifespan = models.IntegerField(null=True, blank=True) dimmable = models.BooleanField(default=False) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class LEDData(models.Model): average_lifespan = models.IntegerField() dimmable = models.BooleanField(default=True) voltage = models.DecimalField(max_digits=5, decimal_places=2, null=False) flicker_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) stroboscopic_effect_metric = models.DecimalField(max_digits=2, decimal_places=1, null=True) class Luminaire(models.Model): product = models.OneToOneField(Product, primary_key=True) control_gear_included = models.BooleanField(default=True) external_control_gear = models.BooleanField(default=True) control_gear_changeable = models.BooleanField(default=True) control_gears = models.ManyToManyField('ControlGear', through='LuminaireControlGearDetails') led_data = models.ForeignKey(LEDData) lighting_technology = models.CharField(max_length=15, choices=LightingTechnology, default=LightingTechnology.LED) ... class … -
Django App is delayed or does not reflect the changes in the new code
We have a django app deployed to AWS EC2 instances (autoscaled) via codedeploy. The deployment is successful, and I can see the new code when connected to the instances. However, the django app did not reflect the changes in the new code. Why is that? We also had a case when we did a database migration and the new fields only showed up 1 day later. WE foudn the DNS Time-To-Live (TTL) value is set to 2 days by default, which we have now updated it to a shorter timeframe. However, it hasn't made any progress. Have also restarted the servers etc. -
How to validate JWT tokens on Angular Frontend?
Please help me! I have a study project. There is a Frontend based on Angular 17 and a Backend based on Django Rest Framework. The user should be able to login through a third party API (like Google login). In my code, when a user on Fronend clicks the “log in via API” button, I redirect him to the Backend, then to a third-party service, he logs in there and the backend receives a response from the third-party service that everything is OK. Then on the Backend I create 2 JWT tokens and send them to the query string GET request to the Frontend. Frontend catches this request and authorizes the user, but it DOES NOT CHECK the tokens that they were issued by the backend and that they are correct, but only stores them in the user’s browser. That is, if I make the same request directly from the browser but with a fake secret in the token, then the user is still authorized! The question is - how to fix this? How to check tokens to ensure that they are not fake and send by backend? chatgpt and google a lot -
How to remove duplicated migration having same content in django
if we created a procedure in django project and then we need to changed variables or any changes in content. then same named procedure duplicates . we need to remove it 0002_remove_whocanapprove_approver_level_and_more 0004_remove_whocanapprove_approver_level_and_more this 2 are same then remove first one -
Django Admin - show a secondary table of related objects in the admin list view
I'm having a Django project which applies Admin pages only, i.e. no User pages at all. I'm specifically applying the Admin-UnFold flavor, with a slightly enhanced UI. Assume having 2 classes named AAA and BBB, where BBB has a ForeignKey named aaa. ( AAA may have multiple related BBBs ) Now, when listing the AAA instances, is it possible to maintain a secondary (new) table below the main one, which previews all related BBB objects for a selected AAA? The selection may be achieved with a new designated column in the main table, with "preview" button/hyperlink. From the user perspective (UI), clicking on the "preview" in the main table will allows a quick look on the corresponding related objects. Thanks ahead, Shahar -
Django GenerateSeries return same row multiple times
I've an appointment model with starts_at, repeat_duration I want to annotate the repeating values returned from a generated series the sum duration field till the end date so if date of appointment on 14-07-2024, end_date is 25-07-2024 and duration is 3 days it return 14, 17, 20, 23 as an array annotation but what I'm getting is the same object, returned multiple times and each time it has one value of the series result for the example it'll be returned four times one for each value and repeat_days will be this value object_1.repeat_days = 14 object_2.repeat_days = 17 how to make it return only one object and the values as an array tried arrayagg to wrap the GenerateSeries but I'm getting aggregate function calls cannot contain set-returning function calls class AppointmentQuerySet(models.QuerySet): def annotate_repeated_days(self, end_date): return self.annotate( repeat_dates=ArrayAgg( GenerateSeries( models.F("starts_at"), models.F("repeat_duration"), end_date ) ) ) function: from django.db import models class GenerateSeries(models.Func): function = 'generate_series' output_field = models.DateTimeField() def __init__(self, start, step, stop, **extra): expressions = [ start, stop, step ] super().__init__(*expressions, **extra) any ideas? -
How to give permissions to users in django.?
I am building a django ERP project, in which there will be multiple user's, admin,user, manager etc. Each of this user has separate user credentials to login. Each user have separate dashboard. I'm using local database for login function. I want to give access to every user from admin dashboard, like view, edit,and delete, allow them to download csv file. I am trying to make privilege page for each user in admin dashboard. When a radio button or check box turn on, that respective user had to access the privilege. -
NoReverseMatch at /users/reset/done/
this is my url file after getting link on terminal and typing new password i am getting this message when i hit to submit, eventually password is reset but i am getting the error NoReverseMatch at /users/reset/done/ i tried without using templates and with custom templates of my own this is a github link of project https://github.com/agrawalaman4310/Social_Project.git -
gunicorn: command not found when hosting on Railway
I am new to Django and hosting web applications, and I am trying to host my first one using Railway. The application successfully builds and deploys for about 5 seconds before crashing and giving me the error /bin/bash: line 1: gunicorn: command not found. It then tries to repeatedly restart the container, failing every time. I have a Procfile with the line web: gunicorn EPLInsights:app, created the requirements.txt file using pip freeze > requirements.txt, and specified the runtime. I also have whitenoise installed, DEBUG set to false, and ALLOWED_HOSTS set to ['*']. Unfortunately, there is not much more information that Railway presents with the error, so I am having trouble figuring out what is causing it. If anyone has any insight it would be greatly appreciated. -
Django: Manager isn’t available; ‘auth.User’ has been swapped for ‘userauths.CustomUser’
I’m working on a Django project and encountering an issue when trying to sign up a new vendor. The error message I’m getting is: AttributeError at /vendorpannel/vendor_signup/ Manager isn't available; 'auth.User' has been swapped for 'userauths.CustomUser' What I’ve Tried: 1.Ensured AUTH_USER_MODEL is set correctly in settings.py: AUTH_USER_MODEL = 'userauths.CustomUser' 2.Updated references to the user model using get_user_model(): from django.contrib.auth import get_user_model User = get_user_model() 3.Checked and updated forms to use the custom user model: from django import forms from vendorpannel.models import * from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.db import transaction class VendorProfileForm(forms.ModelForm): class Meta: model = VendorProfile fields = [ 'company_name', 'contact_number', 'address', 'city', 'state', 'zip_code', 'country', 'website', 'profile_image', 'bio' ] 4.Updated admin configuration to use the custom user model: from django.contrib import admin from vendorpannel.models import VendorProfile from django.contrib.auth import get_user_model @admin.register(VendorProfile) class VendorProfileAdmin(admin.ModelAdmin): list_display = ('user', 'company_name', 'contact_number', 'city', 'state', 'country') Here are the relevant parts of my code: CustomUser model in userauths app: class CustomUser(AbstractUser): username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() Vendor Signup View: def vendor_signup(request): if request.method == 'POST': form = VendorSignupForm(request.POST, request.FILES) if form.is_valid(): user = form.save() login(request, user) … -
Django redirect url not functioning as expected
So I am making a simple django project where me as a superuser, I can make restaurant instances and it will make a landing page for each restaurant. I have two admin panels, one is the main one, which is for superuser and the other is for restaurant owners who have the is_restaurant_admin set to true. Now the problem is, after stripe onboarding when I make a restaurant instance from admin panel, it redirects me to http://127.0.0.1:8000/restaurant-admin/login/?next=/restaurant-admin/%3Fstripe_onboarding_completed%3Dtrue even though I explicitly wrote the logic to redirect me to main admin page. Can anyone point out where the problem is please? Thanks! My models.py: class Restaurant(models.Model): name = models.CharField(max_length=100) email = models.EmailField() description = models.TextField() image = models.ImageField(upload_to='restaurant_images/') banner_image = models.ImageField(upload_to='restaurant_images/', null=True) primary_color = models.CharField(max_length=7) # Hex color code secondary_color = models.CharField(max_length=7) # Hex color code favicon = models.FileField(upload_to='restaurant_favicons/', null=True, blank=True) about_text = models.TextField(blank=True, null=True) map_iframe_src = models.TextField(blank=True, null=True) slug = models.SlugField(unique=True, max_length=100, null=True) stripe_account_id = models.CharField(max_length=255, null=True, blank=True) stripe_account_completed = models.BooleanField(default=False) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.name) super().save(*args, **kwargs) def __str__(self): return self.name class RestaurantUser(AbstractUser): restaurant = models.OneToOneField(Restaurant, on_delete=models.CASCADE, null=True, blank=True) is_restaurant_admin = models.BooleanField(default=False) def save(self, *args, **kwargs): if self.is_restaurant_admin: self.is_staff = True super().save(*args, **kwargs) My … -
How come I can't get my GET requests to work but I POSTS works fine?
I am working on my first webapp. I can sign up a user or log in a user and the user is stored in my database and a authentication token is generated when they log in. I can successfully have the user create a new venture profile which stores in my database and has a foreign key to associate the venture with the user. So POST is working fine. I am trying to use GET to send data from the database back to the front end and nothing I do will work. I have checked the code over and over and over and it still seems like the endpoint can't be found. This is my front end file which is supposed to display users ventures and its just saying "failed to fech user ventures" async function fetchUserVentures() { try { const token = localStorage.getItem('token'); const response = await fetch('http://localhost:3000/api/ventures', { headers: { 'Authorization': `Bearer ${token}` } }); if (!response.ok) { throw new Error('Failed to fetch user ventures'); } const data = await response.json(); userVentures.set(data); } catch (err) { error.set(err.message); } }` This is from my ventures.js file in routes folder in backend: router.get('/', authenticateToken, async (req, res) => { try … -
How to save css to persist over loading different pages or refreshing page
I am trying to implement the function of saving a post or liking a post and the css style of the like button or the save button doesn't apply when refreshing or changing page. how can I save the css styles to persist over different pages. I am using django in the backend here is my view in django: def favourite(request, post_id): user = request.user post = Post.objects.get(id=post_id) profile = Profile.objects.get(user=user) is_favourite = False if profile.favourite.filter(id=post_id).exists(): profile.favourite.remove(post) is_favourite = False else: profile.favourite.add(post) is_favourite = True response = { "is_favourite": is_favourite, } return JsonResponse(response) here is the html/css/js part: $(document).ready(function () { $('.favourite-button').click(function (e) { e.preventDefault(); var button = $(this); var post_id = button.data('id'); var url = button.attr('href'); $.ajax({ type: 'POST', url: url, data: { 'csrfmiddlewaretoken': '{{ csrf_token }}', }, success: function (response) { if (response.is_favourite) { button.find('i').addClass('liked'); } else { button.find('i').removeClass('liked'); } }, error: function (response) { console.error('Error:', response); } }); }); }); .action-buttons i.liked{ color: var(--btn-color); } <div class="action-buttons"> <div class="interaction-buttons"> <span> <a href="{% url 'like' post.id %}" class="like-button" data-id="{{ post.id }}"> <i class='bx bxs-heart {% if post.user_liked %} liked {% endif %}'></i> </a> </span> <span><i class='bx bxs-comment-detail'></i></span> <span><i class='bx bxs-share-alt'></i></span> </div> <div class="bookmark"> <span> <a href="{% url 'favourite' … -
Django accounts custom AuthenticationForm failing as invalid
Why is this giving form invalid? My username password input is correct. forms.py class CustomAuthForm(AuthenticationForm): username = forms.CharField(required=True, max_length = 50, widget=forms.EmailInput(attrs={"placeholder": "Email", "class":"form-control"})) password = forms.CharField(required=True, max_length = 50, widget=forms.PasswordInput(attrs={"placeholder":"Password", "class":"form-control"})) views.py @csrf_protect def user_login(request): if request.user.is_authenticated: return redirect('/') form=CustomAuthForm(request.POST or None) print(request.POST) if form.is_valid(): print(form.cleaned_data) else: print ('form invalid') Console print <QueryDict: {'csrfmiddlewaretoken': ['mt5a3e9KyCbVg4OokaDeCu97EDrHVInAwVJmmK3a2xn0Nn4KRi0gt7axWJyRDMmT'], 'username': ['myemail@gmail.com'], 'password': ['mypass']}> form invalid -
Query perfomance for main table with many-to-many relation in Django painfully slow on staging environment
I have a Django app which works with geodata. Querying the main table from Djangos ORM containing some larger polygons is all in all ridiculously slow, especially on our staging environment. The table currently has ~50k entries. A simple count over it with one boolean filter takes (times for ORM taken from Django Debug Toolbar, for raw SQL I copied the resulting SQL from there as well and ran it in psql shell): on my dev machine from Django ORM: ~600ms raw SQL: ~60ms on our staging instance from Django ORM: ~12s raw SQL: ~80ms What can cause this gigantic overhead? I find 10x on my local machine already heavy, but almost 200x on the staging instance just renders the application useless. How does Django Debug Toolbar measure the time for SQL execution? I suppose it could be some networking issue, so I already tested a database running in docker on staging instance and a hosted DB by AWS, same results. -
Validating POST parameters with serializers in Django
I'm trying to implement a simple validator for my POST parameters My input looks like this: { "gage_id": "01010000", "forcing_source":"my_source", "forcing_path":"my_path" } I have the following Serializer: class SaveTab1Serializer(Serializer): gage_id = CharField(min_length=1, required=True), forcing_source = CharField(min_length=1, required=True), forcing_path = CharField(min_length=1, required=True), And I use it like this: @api_view(['POST']) def save_tab1(request): body = json.loads(request.body) ser = SaveTab1Serializer(data=body) print('serializer', ser.is_valid()) print('errors', ser.errors) But now matter what I do with the data, it only shows as valid with no errors. Is there more code that I need to add to the serializer to do the validation? -
Unexpected sort order in bootstrap-table
Not sure if I'm doing something dumb or what, but I have a table initialized with data='table' A header like <th data-sortable="true" data-field='col_display_name' class="text-center th-lg "scope="col">{% trans site_display_name_header %}</th> And data that looks like this <td class="ml-5"> <a href="{% url 'sites:site_detail' site.id %}">{{ site.site_display_name }}</a> </td> However sorting the column just seems to toggle the sort between the default order and the reverse order, and doesn't seem related to the data in the column (site.site_display_name) Other columns in the table are setup the same way and seem to sort correctly based on the values in the column. There is no leading or trailing characters or anything that stands out that would make me think it is sorting correctly. My understanding from the bootstrap-table documentation is that if you use data-toggle='table' it automatically figures out the structure of the data and value specified in data-field='col_display_name' can really be anything you want to call it (as long as its unique I imagine). Any idea what I'm doing incorrectly?