Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Static files not loading Classes properly in Django
I am having problems with Django to properly load the css classes style into the template. The problem is with certain semantic tags and I can't understand what is the problem. My Html and CSS code : .main { width: 100%; height: 100%; display: inline-flex; height: auto; } .main .left-main { width: 450px; height: auto; margin: 40px; display: block; } .main .left-main .post-container { width: 100%; height: auto; background: white; display: inline-flex; border: 0.5px solid #377976; margin-bottom: 50px; } .main .left-main .post-container .post-left { width: 85px; display: block; } .main .left-main .post-container .post-left .post-left-top { margin-top: 7px; margin-left: 7px; background: #C0C0C0; width: 80px; height: 65px; border-radius: 50%; border: 1px solid black; box-shadow: gray 0 0 10px; } .post-upper { margin-left: 23px; height: 25px; display: inline-flex; width: 275px; padding-top: 12px; border-bottom: 1px solid #C0C0C0; position: relative; } .post-upper .post-author { margin-left: 9px; } .post-upper .post-date_posted { position: absolute; right: 0; } .post-upper .post-author h1 { font-family: Courier New; text-decoration: none; color: black; } .post-upper .post-date_posted h1 { color: #666; font-family: monospace; font-weight: 400; font-size: 16px; } .post-bottom { color: black; display: block; } .post-bottom .post-title { min-height: 30px; height: auto; text-align: left; margin: 15px 10px 0 35px; } .post-bottom .post-title h1 … -
Django 3 - Select a valid choice. That choice is not one of the available choices
I'm trying to build a project management application. However, when I try to submit form in add_project.html, Django throws a "Select a valid choice. That choice is not one of the available choices." error. I have a Postgresql database. Can you give me a hint what might be wrong? models.py from django.db import models from datetime import datetime from clients.models import Client from engineers.models import Engineer from agents.models import Agent from systems.models import System from rals.models import Ral class Project(models.Model): Status_calculation = ( ('Undistributed', 'Undistributed'), ('No info', 'No info'), ('In progress', 'In progress'), ('Calculated', 'Calculated'), ) Status_project = ( ('Contracted', 'Contracted'), ('Lost', 'Lost'), ('Pending', 'Pending'), ) Attribute = ( ('A', 'A'), ('B', 'B'), ('C', 'C'), ) client = models.ForeignKey(Client, on_delete=models.DO_NOTHING) entry_date = models.DateField(blank=True) exit_date = models.DateField(blank=True) project = models.CharField(max_length=200) parent_id = models.IntegerField(null=True, blank=True) attribute = models.CharField( max_length=200, null=True, blank=True, choices=Attribute) engineer = models.ForeignKey(Engineer, on_delete=models.DO_NOTHING) agent = models.ForeignKey(Agent, on_delete=models.DO_NOTHING) system = models.ForeignKey(System, on_delete=models.DO_NOTHING) ral = models.ForeignKey(Ral, on_delete=models.DO_NOTHING) surface = models.IntegerField() profile_price = models.IntegerField() acc_price = models.IntegerField() total_price = models.IntegerField() proforma = models.CharField(max_length=200) file_number = models.CharField(max_length=200) status_calculation = models.CharField( max_length=200, null=True, choices=Status_calculation) status_project = models.CharField( max_length=200, null=True, choices=Status_project) obs = models.TextField(blank=True) working_time = models.IntegerField() class Meta: verbose_name_plural = 'Projects' def __str__(self): return … -
Why urls order is important in django for different named urls?
I have two urls in my urls.py file url('to_quotation/$', views.to_quotation, name='to_quotation'), url('turn_into_quotation/$', views.turn_into_quotation, name='turn_into_quotation'), and i have two view for them in views.py. When i make an ajax call to 'turn_into_quotation' url, 'to_quotation' view works. But if i changed my urls.py as: url('turn_into_quotation/$', views.turn_into_quotation, name='turn_into_quotation'), url('to_quotation/$', views.to_quotation, name='to_quotation'), it works properly. What is the reason for that? -
django unique together just if
I want to use unique together just if the post_type is index 1. For every section to be possible to choose article type index 1 only one time but possible to chose index 0 with no limitation. ''' class Post(models.Model): Article_type = (('news', 'Het laatste nieuws'), ('introduction', 'Een introductie')) post_id = models.AutoField(primary_key=True) post_title = models.CharField(max_length=50, null=False) post_header = models.TextField(max_length=250, null=True, blank=True) post_body = RichTextUploadingField(null=True) post_expire_date = models.DateTimeField(null=True, blank=True) post_available_date = models.DateTimeField(default=timezone.now, null=False) post_image = models.ImageField(upload_to='post-uploads/', null=True, blank=True) post_section = models.ForeignKey(Section, on_delete=models.CASCADE, default=1) post_type = models.CharField(max_length=30, choices=Article_type, default="news") post_author = models.ForeignKey( user, on_delete=models.CASCADE, limit_choices_to={'is_staff': True}, null=True, default=user, ) slug = models.SlugField(unique=True) ''' -
Django ModelForm has no model class specified, Although model in Meta class is set to a model
Error is "ModelForm has no model class specified." forms.py code from django.contrib.auth.models import User from basic_app.models import UserProfileInfo class UserForm(forms.ModelForm): password = forms.CharField(widget=forms.PasswordInput()) class Meta(): models = User fields = ('username', 'email', 'password') class UserProfileInfoForm(forms.ModelForm): class Meta(): model = UserProfileInfo fields = ('portfolio_site', 'profile_pic') models.py code from django.db import models from django.contrib.auth.models import User # Create your models here. class UserProfileInfo(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) #additional portfolio_site = models.URLField(blank=True) profile_pic = models.ImageField(upload_to='profile_pics', blank=True) def __str__(self): return self.user.username views.py code from django.shortcuts import render from basic_app.forms import UserProfileInfoForm, UserForm # Create your views here. def index(request): return render(request, 'basic_app/index.html') def register(request): registered = False if request.method == 'POST': user_form = UserForm(data=request.POST) profile_form = UserProfileInfoForm(data=request.POST) if user_form.is_valid() and profile_form.is_valid(): user = user_form.save() user.set_password(user.password) user.save() profile = profile_form.save(commit=False) profile.user = user if 'profile_pic' in request.FILES: profile.profile_pic = request.FILES['profile_pic'] profile.save() registered = True else: print(user_form.errors, profile_form.errors) else: user_form = UserForm() profile_form = UserProfileInfoForm() return render(request, 'basic_app/registration.html', {'user_form' : user_form, 'profile_form' : profile_form, 'registered' : registered}) The error is occurs when I'm trying to create a new user form (user_form = UserForm()). Although in my meta class I set models to the User model imported from django.contrib.auth.models. Error Info Picture -
How to make a secure connection to ec2 instance on aws
I have managed to connect my ec2 instance to my domain with route 53. However im now having issues making the connection secure. I have tried to follow step by step instructions found on stack exchange however am still having issues and wonder if anyone can help me. I created a secure certificate with the amazon certificate manager and connected this to a load manager which is linked to my ec2 instance. I then used the DNS name on the load balancer and added this to my route 53 configuration. Something I cant quite understand is when I test the record set on route 53 I get the IP 3.129.2.237 returned (which still loads the ec2 instance), not the ip4v value found on the ec2 instance 18.217.221.40. Ive then taken the name server values and put them into my dynadot (host) name server settings. I have restarted my gunicorn server that im using on the ec2 instance. It is running on port 9090, in the Nginx settings (/etc/nginx/sites-available/default) I set proxy_pass to http://0.0.0.0:9090. The site runs when doing a http:// request (http://www.advancedmatchedbetting.com)but not when a https request occurs enter link description here. If anyone has any idea where im going … -
Displaying model fields in django in a dropdown list
so I'm writting a program for creating orders for specific users and items. My problem is when I'm trying to display all customers, products and statuses from this model: class Order(models.Model): STATUS = ( ('Pending', 'Pending'), ('Out for delivery', 'Out for delivery'), ('Delivered', 'Delivered'), ) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) date_created = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=20, null=True, choices=STATUS) def __str__(self): return self.product.name I have to do this manually: {% extends 'accounts/base.html' %} {% load static %} {% block main %} <form action="" method="post"> {% csrf_token %} <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> customer </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" > {{ form.customer.1 }}</a> <a class="dropdown-item" > {{ form.customer.2}}</a> <a class="dropdown-item" > {{ form.customer.3}}</a> <a class="dropdown-item" > {{ form.customer.4}}</a> <a class="dropdown-item" > {{ form.customer.5}}</a> </div> </div> <input type="submit" name="submit" class="btn btn-success"> </form> {% endblock %} That's because when i tried making a loop which would just give them ids instead of numbers it just wouldn't show up. Can anybody help me? :( -
django allauth URL patterns are incorrect
I have just finished installing allauth and plan to use it in my site, however currently the URL patterns don't work. If i set it as the following urlpatterns = [ ... path('accounts/', include('allauth.urls')), ... ] and go to /accounts/discord/ it gives a 404 and says the correct URLs are accounts/ social/ accounts/ discord/ login/ [name='discord_login'] accounts/ discord/ login/callback/ [name='discord_callback'] Notice the extra space after each step. This is the same for all of the allauth URLs Because of this, I cannot access the right pages to login. How do i fix this? or is this some strange bug -
Error: unindent does not match any outer indentation
my django code shows me this error unindent does not match any outer indentation, read that it's about tabs and spaces, but nothing works for me. I will appreciate if someone take a look into my code. views.py from django.shortcuts import render, redirect from django.http import HttpResponse # Create your views here. from .models import * from .forms import OrderForm from .filters import OrderFilter def home(request): orders = Order.objects.all() customers = Customer.objects.all() total_customers = customers.count() total_orders = orders.count() delivered = orders.filter(status='Delivered').count() pending = orders.filter(status='Pending').count() context = {'orders':orders, 'customers':customers, 'total_orders':total_orders,'delivered':delivered, 'pending':pending } return render(request, 'accounts/dashboard.html', context) def products(request): products = Product.objects.all() return render(request, 'accounts/products.html', {'products':products}) def customer(request, pk_test): customer = Customer.objects.get(id=pk_test) orders = customer.order_set.all() order_count = orders.count() **myFilter = OrderFilter()** context = {'customer':customer, 'orders':orders, 'order_count':order_count, 'myFilter': myFilter} return render(request, 'accounts/customer.html',context) def createOrder(request, pk): customer = Customer.objects.get(id=pk) form = OrderForm(initial={'customer': customer}) if request.method == 'POST': #print('Printing POST:', request.POST) form = OrderForm(request.POST) #sending data into the form if form.is_valid(): form.save() return redirect('/') context = {'form': form} return render(request, 'accounts/order_form.html', context) def updateOrder(request, pk): #prefill forms after click update order = Order.objects.get(id=pk) form = OrderForm(instance=order) #save the changes if request.method == 'POST': form = OrderForm(request.POST, instance=order) #sending data into the form if form.is_valid(): form.save() … -
Render svg content Django
I have static svg file inside my images folder. I'd like to render actual svg content inside my anchor tag. I tried {% static "images/blog/facebook-icn.svg" %} and it just parse it as a string. what is the function to render actual content of svg file inside html? The code: {% load staticfiles %} <a href="http://www.facebook.com/sharer/sharer.php?u=my-site{{ request.get_full_path|urlencode }}" target="_blank" class="facebook"> {% static "images/blog/facebook-icn.svg" %} </a> -
How set Foreign key value as email not ID?
I have User Model and Favorite Product Model. I have link as ID to user in Favorite Product model. Can I change ID link to email? This is my User Model. 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) surname = models.CharField(max_length=255, default='Фамилия') is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) favorite_product = models.ForeignKey( 'FavoriteProduct', related_name='favorite_products_for_user', on_delete=models.SET_NULL, null=True ) objects = UserManager() USERNAME_FIELD = 'email' This is my Favourite Product model class FavoriteProduct(models.Model): """Favorite product object""" created = models.DateTimeField(auto_now_add=True, null=True) product = models.ForeignKey( 'Product', related_name='favorite_products', on_delete=models.CASCADE, null=True ) user = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) If you do not undersatnd me? I uploaded picture.png file.enter image description here -
Django: def save() in models.py
I'm trying to add the save-function inside my models.py, but it seems I'm doing something wrong. The user has to type the first- and last-name. Without him or her entering any more data, another field inside my models.py should be filled with a combination from these fields. models.py: class Coworker(models.Model): first_name = models.CharField(max_length=50, null=False, blank=False) last_name = models.CharField(max_length=50, null=False, blank=False) full_name = models.CharField(max_length=100, null=False, blank=False) def save(self, *args, **kwargs): self.full_name = self.first_name + " " + self.last_name super().save(*args, **kwargs) Is this even possible? Thanks for all your help. Have a nice weekend! -
Django Video Encoding package not converting videos
hey guys I am trying to add the django-video-encoding package, but it doesn't seem to be working. I have followed exactly as per the documentation. Can someone help with checking the code I have if I missed anything? This is the link to the package: https://github.com/escaped/django-video-encoding Can anyone tell me where I went wrong? I couldn't see any tutorials or much info regarding this package but it seems like its the only one there. I have given the path to ffmpeg like this (am not sure whether its the right way). this is in settigs. VIDEO_ENCODING_FFMPEG_PATH = "c:\\ffmpeg\\bin\\ffmpeg.exe" in my signals.py I have this. @receiver(post_save, sender=VideoPost) def convert_video(sender, instance, **kwargs): enqueue(tasks.convert_all_videos, instance._meta.app_label, instance._meta.model_name, instance.pk) print('Done converting!') and this prints after I upload a video, but the conversion is not happening. -
Django initialize model formset with instances
I have following model: class ModelA(models.Model): name = models.CharField(max_length=100) description = models.CharField(max_length=100) And it is used in modelformset: ModelAFormSet = generic_inlineformset_factory( ModelA, form=AddModelAForm, extra=2) where AddModelAForm looks like this: class AddModelAForm(forms.ModelForm): selected = forms.BooleanField(required=False) class Meta: model = ModelA fields = ['id'] and then initialized following way: formset = ModelAFormSet( queryset = ModelA.objects.none(), initial=[{'id':16, 'selected': True}, {'id': 32, 'selected': False}]) I would like to use in template instance, instead of actual model fields. Something like this: {{formset_form.id}} {% with formset_form.instance as modelA %} Name: {{modelA.name}} Description: {{modelA.description}} {{formset_form.selected}} {% endwith %} Which is working with such instantiation of ModelAFormSet: formset = ModelAFormSet(queryset=ModelA.objects.all()) I know I could use change Meta class of AddModelAForm to have fields = ['id', 'name', description'] and then initialize those values. But in this case I can no longer use instance, but regular fields values (e.g. {{formset_form.name.value}}). And because of that I need to have something like this in clean() method of my form: def clean(self): try: del self.errors['name'] del self.errors['description'] except KeyError: pass I'd like to ask if there is any better way to have such formset initialized and doesn't need to remove errors explicitly? -
Django 3.1: OperationalError - No Such Column/Table
I've been solving this problem for the entire day. My code in my models.py is the following: from django.db import models from django.contrib.auth.models import User from users.models import TeacherProfile, StudentProfile class Course(models.Model): name = models.CharField(max_length=100) desc = models.TextField() short_code = models.CharField(max_length=5) teacher = models.ForeignKey(TeacherProfile, null=True, on_delete=models.SET_NULL) students = models.ManyToManyField(StudentProfile) def __str__(self): return self.name class Partition(models.Model): name = models.CharField(max_length=20) chunk = models.FloatField() result = models.FloatField(blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) def __str__(self): return self.name class Activity(models.Model): title = models.CharField(max_length=100) content = models.TextField() file = models.FileField(blank=True) course = models.ForeignKey(Course, on_delete=models.CASCADE) parent = models.ForeignKey(Partition, on_delete=models.CASCADE) def __str__(self): return self.title class Grade(models.Model): grade = models.FloatField() remarks = models.CharField(max_length=200, blank=True) activity = models.ForeignKey(Activity, on_delete=models.CASCADE) student = models.ForeignKey(StudentProfile, on_delete=models.CASCADE) I've ran the following commands: python manage.py makemigrations python manage.py migrate I even written the following command as per my research to other StackOverFlow questions related to this: python manage.py migrate --run-syncdb Only the Course table worked. The Activity and the Grade table received OperationalError - No Such Column and the Partition Table got an OperationalError - No Such Table. Activity OperationalError at /admin/course/activity/ no such column: course_activity.parent_id Request Method: GET Request URL: http://127.0.0.1:8000/admin/course/activity/ Django Version: 3.1 Exception Type: OperationalError Exception Value: no such column: course_activity.parent_id Exception Location: … -
Bad request 400 while trying to do partial update with UpdateAPIView
I am using DRF UpdateAPIView to take in PATCH method and partially update my model. It should by default handel correctly partial update but i somehow get Bad request error. What could be issue here? View: class ProfileViewUpdate(generics.UpdateAPIView): queryset = Profile.objects.all() serializer_class = ProfileSerializer lookup_field = 'token' lookup_url_kwarg = 'pk' def partial_update(self, request, *args, **kwargs): kwargs['partial'] = True return self.update(request, *args, **kwargs) Serializer: class ProfileSerializer(serializers.ModelSerializer): class Meta: model = Profile fields = ('token', 'bio', 'name', 'email', 'sport', 'location', 'image') -
How to get GDAL to work with Google GCLOUD
I am getting the below error trying to deploy my app to gcloud app engine. The whole problem is from trying to add the GDAL library to my app. File "/opt/python3.7/lib/python3.7/ctypes/init.py", line 377, in getattr func = self.getitem(name) File "/opt/python3.7/lib/python3.7/ctypes/init.py", line 382, in getitem func = self._FuncPtr((name_or_ordinal, self)) AttributeError: /usr/lib/libgdal.so.1: undefined symbol: OGR_F_GetFieldAsInteger64 I followed all the directions I could possibly find online. But nothing seems to work at all. Here is my app.yml files: runtime: custom entrypoint: gunicorn -b :8080 app.wsgi env: flex # any environment variables you want to pass to your application. # accessible through os.environ['VARIABLE_NAME'] env_variables: ... beta_settings: cloud_sql_instances: site:asia-northeast2:site-db handlers: - url: /.* script: auto secure: always manual_scaling: instances: 1 runtime_config: python_version: 3 And Dockerfile: FROM gcr.io/google-appengine/python #FROM python:3.7 #FROM python:3.8.0-slim-buster EXPOSE 8080 ENV PYTHONUNBUFFERED 1 # Install GDAL dependencies #RUN apt-get update && apt-get install --yes libgdal-dev RUN apt-get update && apt-get install --reinstall -y \ #libopenjp2-7 \ #libopenjp2-7-dev \ #libgdal-dev \ binutils \ gdal-bin \ python-gdal \ python3-gdal # Update C env vars so compiler can find gdal #ENV CPLUS_INCLUDE_PATH=/usr/include/gdal #ENV C_INCLUDE_PATH=/usr/include/gdal RUN export CPLUS_INCLUDE_PATH=/usr/include/gdal RUN export C_INCLUDE_PATH=/usr/include/gdal # Create a virtualenv for dependencies. This isolates these packages from # system-level packages. # … -
Best way to implement background “timer” functionality in Python/Django
I am trying to implement a Django web application (on Python 3.8.5) which allows a user to create “activities” where they define an activity duration and then set the activity status to “In progress”. The POST action to the View writes the new status, the duration and the start time (end time, based on start time and duration is also possible to add here of course). The back-end should then keep track of the duration and automatically change the status to “Finished”. User actions can also change the status to “Finished” before the calculated end time (i.e. the timer no longer needs to be tracked). I am fairly new to Python so I need some advice on the smartest way to implement such a concept? It needs to be efficient and scalable – I’m currently using a Heroku Free account so have limited system resources, but efficiency would also be important for future production implementations of course. I have looked at the Python threading Timer, and this seems to work on a basic level, but I’ve not been able to determine what kind of constraints this places on the system – e.g. whether the spawned Timer thread might prevent the … -
django clear stale cache entry
I am using database as cache backend. CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.db.DatabaseCache', 'LOCATION': 'cache_table', } } The problem is that after few times, there are stale entries which are not getting cleared up. Do I need to configure something to get them cleared once they are stale (past their expiration date)? Or need to setup some job to clear? I tried using cache.clear(). But it clears up the non-expired entries as well. -
How to hide all forms in a formset except the clicked one in django template
I am new to Django. I recently started to work with Django-formset, I have 12 forms in Django-formset, each form has atleast 20 fields. My requirement is make a user-friendly design. I decided to make 12 buttons in a row corresponding to each form, initially all the forms will be hidden. When I click on one button, let's say first button then only form corresponding to that button will show up in the same page and rest of the forms will hide. If user click on the same button again then the form should collapse, if user click on other button then form corresponding to that button should show and rest of the forms should hide. After a lot of reading online I could not find a solution to this problem but I came to know that I need to use jQuery or javaScript to solve this. Here is what I have tried so far, but it only hide/show the form that I have clicked and not affect other forms. <form action="{% url 'my_formset' %}" method="POST"> {% csrf_token %} {{ formset.management_form }} {{ formset.non_form_errors.as_ul }} <h4> Time </h4> {% for form in formset %} <a id="{{forloop.counter}}-btn" class="btn btn-success mt-2">{{ form.time.value … -
Django got an unexpected keyword argument error
I am trying to create form to save some Data and I start it with model called it RegisterForm and created other model called Courses and I add new field "Course" to be foreignKey in the RegisterForm Model ,I am try submit the data through html form to database using PostgreSQL , and I got error "got an unexpected keyword argument" My models from django.db import models from django import forms class Courses(models.Model): CourseName = models.CharField(max_length =200) CourseTecher = models.CharField(max_length =100) CoursePrice = models.IntegerField() def __str__(self): return self.CourseName class RegisterForm(models.Model): name = models.CharField(max_length =100) phoneNumber = models.IntegerField() Course = models.ForeignKey(Courses ,related_name='Newreg', on_delete=models.CASCADE) def __str__(self): return self.name My Views from django.shortcuts import render from .models import Courses, RegisterForm def index(request): Course = Courses.objects.all() return render(request ,'index.html' , {'Course' : Course }) def register(request): name = request.POST['name'] phoneNumber = request.POST['phoneNumber'] Nclass = request.POST['Nclass'] NewRegisterForm = RegisterForm(name =name , phoneNumber =phoneNumber , Nclass =Nclass) NewRegisterForm.save() return render(request , 'bill.html') in html page {% for NewRegisterionClass in Course%} <option>{{NewRegisterionClass.CourseName}}</option> {% endfor %} and the error is TypeError at /register RegisterForm() got an unexpected keyword argument 'Nclass' Request Method: POST Request URL: http://127.0.0.1:8000/register Django Version: 3.1 Exception Type: TypeError Exception Value: RegisterForm() got an unexpected … -
Need suggestions : Django UserProfile geographic address to connect with others users
I hope you're well, I'm looking for a plugin or a tutorial for : a- allow my users to fill in their address on their profile. The best would be to have a map on which they can identify their address or like on the UberEats site. b- to be able to find the closest users according to their address. If you have any ideas, I'm interested, I have already made the profile on Django, all I need is the address field. -
Getting MultiValueDictError in fetch GET data django
I am trying to fetch GET data receiving from an HTML form. But it is giving me MultiValueDictError. It is also saying During handling of the above exception, another exception occurred: My HTML code : <!DOCTYPE html> <html> <head> <title>Document</title> </head> <body> <form action="home_redirect/fd" id="redirect" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input type="text" value={{user}} name="user"> <input type="submit"> </form> <script> document.getElementById("redirect").submit() </script> </body> </html> My views.py : def home(request): user = request.GET['user'] return render(request, 'main.html', {'login': user}) -
how to make urls in django rest framework case insensitive
How to make urls case insensitive with certain parameters passed For example, assuming Stock model has a ticker. All links below should find the same ticker content, right now they are case sensitive and try to search for different values: /stocks/AAPL /stocks/aapl /stocks/AaPl views.py class StockViewSet(viewsets.ModelViewSet): queryset = Stock.objects.all() serializer_class = StockSerializer lookup_field = "ticker" @action(detail=True, methods=["get"], url_path="is", url_name="is") def get_income_statement(self, request, *args, **kwargs): is_qs = IncomeStatement.objects.filter(ticker=self.get_object()) serializer = IncomeStatementSerializer(is_qs, many=True) return Response(serializer.data) @action(detail=True, methods=["get"], url_path="bs", url_name="bs") def get_balance_sheet(self, requests, *args, **kwargs): bs_qs = BalanceSheet.objects.filter(ticker=self.get_object()) serializer = BalanceSheetSerializer(bs_qs, many=True) return Response(serializer.data) @action(detail=True, methods=["get"], url_path="cf", url_name="cf") def get_cashflows_statement(self, requests, *args, **kwargs): cf_qs = CashflowsStatement.objects.filter(self.get_object()) serializer = CashflowsStatementSerializer(cf_qs, many=True) return Response(serializer.data) class IncomeStatementDetail(viewsets.ModelViewSet): queryset = IncomeStatement.objects.all() serializer_field = IncomeStatementSerializer class BalanceSheetDetail(viewsets.ModelViewSet): queryset = BalanceSheet.objects.all() serializer_field = BalanceSheetSerializer class CashflowsStatementDetail(viewsets.ModelViewSet): queryset = CashflowsStatement.objects.all() serializer_field = CashflowsStatementSerializer urls.py router = DefaultRouter() router.register(r"stocks", views.StockViewSet) urlpatterns = router.urls models.py class Stock(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, unique=True) ticker = models.CharField(max_length=10, unique=True, primary_key=True) slug = models.SlugField(default="", editable=False) def save(self, *args, **kwargs): value = self.ticker self.slug = slugify(value, allow_unicode=True) super().save(*args, **kwargs) def __str__(self): return self.ticker class Meta: verbose_name = "stock" verbose_name_plural = "stocks" ordering = ["ticker"] -
How to add record after bulk_create objs in django?
I want to add a record for each model object that created by bulk_create method of django, how can I make it work? It seems rewriting save method of model doesn't work. # WarningAccountsSpend class WarningAccountsSpend(models.Model): account_id = models.CharField(max_length=32, blank=True, null=True) date = models.IntegerField(blank=True, null=True) account_type = models.IntegerField(blank=True, null=True) entity = models.CharField(max_length=255, blank=True, null=True) spend_cap = models.BigIntegerField(db_column='spend cap', blank=True, null=True) # Field renamed to remove unsuitable characters. balance = models.BigIntegerField(blank=True, null=True) is_spend_over_yesterday = models.IntegerField(blank=True, null=True) growth_rate = models.IntegerField(blank=True, null=True) account_create_time = models.DateTimeField(blank=True, null=True) is_violated = models.IntegerField(blank=True, null=True) note = models.CharField(max_length=255, blank=True, null=True) created_time = models.DateTimeField(blank=True, null=True) spend = models.DecimalField(max_digits=12, decimal_places=2, blank=True, null=True) class Meta: managed = False db_table = 'warning_accounts_spend' unique_together = (('account_id', 'date'),) ordering = ["-spend"] def save(self, force_insert=False, force_update=False, using=None, update_fields=None): # add operate log # It seems not work here super(WarningAccountsSpend, self).save(force_insert=False, force_update=False, using=None, update_fields=None) # bulk_create model obj WarningAccountsSpend.objects.bulk_create([...], ignore_conflicts=True) How can I add some other operation for object that I bulk created. Thanks.