Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can Django ORM's `.first` return `None` for a non-empty queryset?
I have a very simple model called Achievement. In an algorithm, I reach a point in which I have a queryset for this model - named achievements bellow. I got in a situation in which the method .first() applied to this queryset outputs None, even though there is an element in the queryset. In summary, achievements.order_by('-amount')[0] # outputs an achievement achievements.order_by('-amount').first() # None achievements.count() # 1 How can this happen? There is no default ordering for this model. -
Django Updateview html templet with links using current instance object values
I have two models class AccGroup(models.Model): grpid = models.BigAutoField(primary_key=True, editable=False) groupname = models.CharField(max_length=40, default="") class Meta: indexes = [models.Index(fields=['groupname'])] def __str__(self): return "%s" % (self.groupname) class Account(models.Model): accid = models.BigAutoField(primary_key=True, editable=False) shortcut = models.CharField(max_length=10, default="") accname = models.CharField(max_length=100, default="") accgrp = models.ForeignKey(AccGroup, on_delete=models.RESTRICT, default=0) class Meta: indexes = [models.Index(fields=['shortcut']),models.Index(fields=['accname']) ] def __str__(self): return "%s--%s" % (self.shortcut, self.accname) One Update View defined on above model class AccountUpdateForm(UpdateView): model = Account fields = ['shortcut','accname','accgrp'] def get_success_url(self): currid = self.kwargs['pk'] account = Account.objects.get(pk=currid) print(account) return ('/polls/accmst/'+ str(account.accid)) and the corresponding HTML templet <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Update Account</title> </head> <body> <form action="" method="post"> {% csrf_token %} <table> {{ form.as_table }} </table> <input type="submit" value="Save" /> </form> <p> <a class="btn btn-info btn-sm" href="{% url 'polls:accgrpList' %}">Back To Group List</a> </p> <p> <a class="btn btn-info btn-sm" href="{% url 'polls:accgrpList' form.accgrp.grpid %}">Back To Account List</a> </p> </body> </html> so on success the same page is displayed using the current account object primary key there are two more links Link 1 point the a group list <polls:accgrpList> which translates to http://localhost:8000/polls/accgrplist Link 2 my problem is I want to point to url http://localhost:8000/polls/accgrplist/2 where the last part is the grpid of the current account … -
How to access Other Model Field from Serializer related Field?
have following model class Search(models.Model): trip_choice = ( ('O', 'One way'), ('R', 'return') ) booking_id = models.IntegerField(db_index=True, unique=True) trip_type = models.CharField(max_length=20, choices=trip_choice) and Booking Model is Fk with search class Booking(models.Model) flight_search = models.ForeignKey(Search, on_delete=models.CASCADE) flight_id = models.CharField( max_length=100 ) return_id = models.CharField( max_length=100, blank=True, null=True ) I have following rule if trip type is Return 'R' the return id cannot be sent empty in serializer. class AddBookSerializer(BookSerializer): booking_id = serializers.IntegerField(source='flight_search.booking_id') class Meta(BookSerializer.Meta): fields = ( 'booking_id', 'flight_id', 'return_id', ) def validate_booking_id(self, value): print(value.trip_type) Is there any way I can access trip type based on booking id I am really stuck here. -
Success message not showing after deleting the object in Django rest framework
I have a DestroyAPIView in which I am using the perform_delete function to delete an instance. However, I want to send a success message with 200 status. I tried, but in the postman I am getting blank with 204 status. How can I acheive this?? My view: class UpdateOrderView(UpdateAPIView,DestroyAPIView): permission_classes = [AllowAny] #queryset = Order.objects.prefetch_related('order_items').all() #value = self.kwargs['pk'] queryset = Order.objects.all() print(queryset) serializer_class = OrderUpdateSerializer def perform_destroy(self, instance): if instance.delete(): return Response({ "message":"Order deleted successfully" }, status=status.HTTP_200_OK) else: pass The instance is deleted, I have checked the db, but I am not getting success message. -
show django template engine message in javascript pop up box
I have used django2 to develop a web app. I want to make the text in django template engine showing in js pop up box. <ul class="messages"> {% for message in messages %} <li>{% if message.tags %} "{{ message.tags }} "{% endif %} {{ message }}</li> {% endfor %} </ul> I want to show message in the for loop in js pop up box. How to pass this value to js pop up box in each loop in HTML? -
Django-LDAP Authentication on Login Page
I am having a task to implement the LDAP user authentication on a Django Application. I am quite new to Django and hence facing a lot of issues finding the solution to this question as all the available resources or answers on Stackoverflow are either too old or doesn't have the similar approach which I am using. I have made the changes in my views.py , settings.py , installed all the required packages for ldap to run fine. However I am not getting how to link the ldap with my login form which I have made. I will share my all the changes which I did for the LDAP to work. I will appreciate your time, if you will be able to solve my problem. Here is my : settings.py import ldap AUTH_LDAP_SERVER_URI = "ldap://myldapserver.com" AUTH_LDAP_CONNECTION_OPTIONS = {ldap.OPT_REFERRALS : 0} AUTH_LDAP_USER_DN_TEMPLATE = "uid=%(user)s, OU=USERS,dc=myldapserver, dc=com" AUTH_LDAP_START_TLS = True AUTHENTICATION_BACKENDS = ["django_auth_ldap.backend.LDAPBackend"] views.py from django.contrib.auth import authenticate, login import ldap def ldap_auth(username, password): conn = ldap.initialize(myproj.settings.LDAP_AUTH_URI) try: ldap.set_option(ldap.OPT_REFERRALS, 0) #ldap.set_option(ldap.OPT_PROTOCOL_VERSION, 3) conn.simple_bind_s(username, password) except ldap.LDAPError as e: return f'failed to authenticate' conn.unbind_s() #return "Success" return render(request, 'login.html') #not sure if I need to use the above commented line, as it is … -
Pycharm plugin for autocompletion in Django
I am learning Django for a couple of month now and I've noticed that there's some methods/fields and stuff like that (e.g. get_absolute_url), that Pycharm doesn't offer autocomplition for. So I've been wondering are there any plugins or something for pycharm i can install to make autocomplition more thorough? Thanks in advance! -
Gunicorn worker getting timed out even after processing is success and not returning a Http response
I am using a Django application to do some file processing. I am using an Nginx, Gunicorn, and Django setup. My file processing is being done successfully at the backend level, however, my gunicorn worker is timing out. I have increased the timeout parameter both in Nginx and Gunicorn. -
How to implement django framework nested relationships?
I have tried the option as shown on django rest framework docs, but still it wont work properly.when implementing the nested relashionship I only get the primary key of the lesson, I want all the lesson dedails to apear.Meaning A student has many lessons and I want to allow for each student to show his lessons. Thank you!! My code: Models.py from django.db import models from django.contrib.auth.models import User # from django.utils import timezone from datetime import date class Student(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) information = models.TextField(blank=True) objects = models.Manager() # default manager class Meta: ordering = ('-first_name',) def __str__(self): return self.first_name class Lesson(models.Model): options = ( ('paid', 'Paid'), ('not paid', 'Not Paid'), ) student = models.ForeignKey( Student, on_delete=models.CASCADE, related_name='lessons') paid = models.CharField( max_length=10, choices=options, default='not paid') title = models.CharField(max_length=50) task1 = models.CharField(max_length=50) description1 = models.TextField(blank=True) task2 = models.CharField(max_length=50) description2 = models.TextField(blank=True) user = models.ForeignKey( User, null=True, on_delete=models.CASCADE) lesson_date = models.DateField(default=date.today, null=False) objects = models.Manager() # default manager class Meta: ordering = ('-lesson_date',) def __str__(self): return '%s: %s %s %s' % (self.student, self.title, self.lesson_date, self.paid) Serializers.py from rest_framework import serializers, fields from private_models.models import Lesson, Student class LessonSerializer(serializers.ModelSerializer): #student = serializers.SerializerMethodField() class Meta: model = Lesson fields = … -
Downloaded Django project file raises RelatedObjectDoesNotExist
I have this project that runs correctly on my pc. However, when this project file is pulled/downloaded by other people, RelatedObjectDoesNotExist shows up after createsuperuser. Models.py class User(AbstractBaseUser): email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) first_name =models.CharField(max_length=100) middle_name =models.CharField(max_length=100) last_name =models.CharField(max_length=100) is_active = models.BooleanField(default=True) is_admin = models.BooleanField(default=False) is_chairperson = models.BooleanField(default=False) is_faculty = models.BooleanField(default=False) is_student = models.BooleanField(default=False) objects = UserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'middle_name', 'last_name'] class FacultyInfo (models.Model): fac_user = models.OneToOneField(User, on_delete=CASCADE, primary_key=True) @receiver(post_save, sender=User) def create_or_update_user_profile(sender, instance, created, **kwargs): if created: if instance.is_faculty == True: FacultyInfo.objects.create(fac_user=instance) instance.facultyinfo.save() Full Traceback Traceback (most recent call last): File "E:\iPLM-master2\iPLM-master\manage.py", line 22, in <module> main() File "E:\iPLM-master2\iPLM-master\manage.py", line 18, in main execute_from_command_line(sys.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 419, in execute_from_command_line utility.execute() File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 79, in exe cute return super().execute(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\core\management\base.py", line 398, in execute output = self.handle(*args, **options) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\management\commands\createsuperuser.py", line 189, in ha ndle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "E:\iPLM-master2\iPLM-master\CRS\models.py", line 33, in create_superuser user = self.create_user( File "E:\iPLM-master2\iPLM-master\CRS\models.py", line 26, in create_user user.save(using=self._db) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\base_user.py", line 67, in save super().save(*args, **kwargs) File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 726, in save self.save_base(using=using, force_insert=force_insert, File "C:\Users\DELL\AppData\Local\Programs\Python\Python39\lib\site-packages\django\db\models\base.py", line 774, in save_base … -
Active value in <select> with Django
I have to try to create some html page for add info with Django. I want to use for select my model choice for the first (name='project') and then in the second (name='subsite') I want it filter from the first So, What should I do. My Code: views.py: engineerproductplan.html: base.html: -
How to annotate Django Queryset with the same value but with a different data type of one of existing fields?
I have a Django model that has a NumberVal field which is models.FloatField(). Then I need to annotate the queryset objects like so .annotate(numberval_as_text=str(OuterRef("NumberVal"))) - the same value, but as a string except for the fact that this throws QuerySet.annotate() received non-expression(s): OuterRef(NumberVal) error which is clearly right but it demonstrates the point. I need this because this annotation is followed by an extensive second annotation where I need this numberval_as_text in subquery filters. Any hint would be appreciated. -
Using pandas to load data into Django SQLite causes Exception Value: foreign key mismatch
Is there a reason that I can't place data in sqlite(SQL) using pandas in this situation for a Django model? I would like to use pandas to do some data cleanup and merging of data, then put it into SQL. Before doing the pandas I created my django model. models.py # myapp from django.db import models from django.contrib.auth.models import User class Agency(models.Model): system_name = models.CharField(max_length=255) county = models.CharField(max_length=60) active = models.BooleanField(default=True) system_type_tuple = [('ED', 'School'),('PG','Power Generation'),('TF','Some other Facility'),('UN','Unknown')] system_type = models.CharField(max_length=2, choices=system_type_tuple, default= 'UN') zipcode = models.CharField(max_length=5, null=True, blank=True) agency_no = models.CharField(max_length=7, primary_key=True, unique=True) def __str__(self): return self.agency_no class SitePart(models.Model): system_no = models.ForeignKey('Agency', on_delete=models.CASCADE, db_column='agency_no', null=True, blank=True,) part_name = models.CharField(max_length=125) status_tuple = [('AB','Abandoned'),('AC','Active Compliant'),('DS','Destroyed'),('NP','Need Permit'),('SB','Stand By waiting acitvation')] status = models.CharField(max_length=2, choices=status_tuple, default= 'SB') sys_site_n = models.CharField(max_length=15, unique=True) def __str__(self): return self.part_name To create the SQL database for the above model, I type into terminal the commands: python manage.py makemigrations myapp python manage.py migrate My pandas_script.py is like this: import pandas as pd import sqlite3 as sql import openpyxl import numpy as np conn = sql.connect('C:path_to/Django/my_project/db.sqlite3') support_dir = "C:/.../support/" file1 = support_dir + 'file1.xlsx' file2 = support_dir + 'file2.xlsx' df1 = pd.read_excel(open(file1, 'rb'), engine='openpyxl', sheet_name="Sheet1", usecols = 'A,B,D:G') df2 = … -
Django-Summernote editor not showing in Admin
I have a Django app for post-writing. I've integrated django-summernote to the app but I came across a issue that the django summernote widgets is not showing in admin panel. It is working fine and smooth in my template but its not showing in admin panel. Kindly help me out. settings.py INSTALLED_APPS += ('django_summernote', ) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') X_FRAME_OPTIONS = 'SAMEORIGIN' SUMMERNOTE_CONFIG = { 'iframe': False, "jquery": "summernoteJQuery", 'summernote': { 'width': '100%' } } SUMMERNOTE_THEME = 'bs3' admin.py from django.contrib import admin from .models import Post, Comment from django_summernote.admin import SummernoteModelAdmin class PostAdmin(SummernoteModelAdmin): summernote_fields = ('text',) admin.site.register(Post,PostAdmin) admin.site.register(Comment) urls.py from django.urls import include # ... urlpatterns = [ ... path('summernote/', include('django_summernote.urls')), ... ] ... if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) screenshotAdminPanel -
image is not being uploaded on the website
i have made two identical functions to upload and image and second to upload an additional image. The first one works perfectly but imageSecond dosent work properly. When i upload image it works perfectly but when i upload imageSecond it dosent work properly please i am stuck here from a long time i really need some help. Also, I am using django for backend and react for frontend. Here is the Code: ProductEditScreen.js: const ProductEditScreen = ({ match, history }) => { const productId = match.params.id const [name, setName] = useState('') const [price, setPrice] = useState(0) const [image, setImage] = useState('') const [imageSecond, setImageSecond] = useState('') const [brand, setBrand] = useState('') const [category, setCategory] = useState('') const [countInStock, setCountInStock] = useState(0) const [description, setDescription] = useState('') const [uploading, setUploading] = useState(false) const dispatch = useDispatch() const productDetails = useSelector(state => state.productDetails) const { error, loading, product } = productDetails const productUpdate = useSelector(state => state.productUpdate) const { error: errorUpdate, loading: loadingUpdate, success: successUpdate } = productUpdate useEffect(() => { if(successUpdate){ dispatch({type: PRODUCT_UPDATE_RESET}) history.push('/admin/productlist') }else { if (!product.name || product._id !== Number(productId)) { dispatch(listProductDetails(productId)) } else{ setName(product.name) setPrice(product.price) setImage(product.image) setImageSecond(product.imageSecond) setBrand(product.brand) setCategory(product.category) setCountInStock(product.countInStock) setDescription(product.description) } } }, [dispatch, product, productId, history, … -
Skipping django serializer unique validation on update for the same row
I am using django serializer for validation. The code is listed below. The same code is used for validation checks on creation and updation. However, on the update, the unique validation check on certain fields should be skipped (eg: email). because on update the row will be used. from rest_framework import serializers from rest_framework.validators import UniqueValidator, UniqueTogetherValidator from dashboard.models import Users class UserSerializer(serializers.Serializer): username = serializers.CharField(max_length=200, required=True, validators=[UniqueValidator(queryset=Users.objects.all())]) email = serializers.EmailField(validators=[UniqueValidator(queryset=Users.objects.all())]) def validate_username(self, value): if len(value) < 6: raise serializers.ValidationError('Username must have at least 3 characters') return value def validate_email(self, value): if len(value) < 3: raise serializers.ValidationError('Username must have at least 3 characters') return value def validate(self, data): return data Here, I am using the UniqueValidator, it should be skipped for the update validation check, except for the same row. -
Filtering through date range not working in django rest framework
I am trying to count the total orders made by customers in the last week. I have used ordered_date__range in my view but my API is showing count as zero. I am not sure what is the issue here because I know there are orders made in my db. My view: class DashboardView(ListAPIView): permission_classes = [AllowAny] def get(self, request, *args, **kwargs): count_1 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk']).count() ...................... startdate = datetime.today() + timedelta(days=1) enddate = startdate - timedelta(days=30) count_8 = Order.objects.filter(order_items__item__merchant=self.kwargs['pk'],ordered_date__range=[startdate, enddate]).count() return Response( {'active_users_now': count_2, 'total_customers': count_9, 'total_orders': count_1, 'total_categories': count_3, 'total_subcategories' : count_6, 'total_products_available': count_4, 'total_prodcuts_sold': count_5, 'total_earnings': count_7, 'total_orders_of_the_week': count_8, }, status=status.HTTP_200_OK) Here If I call the above api, my count is showing zero. I just tried adding 2 or 3 orders, but still getting zero counts. I tried removing this part order_items__item__merchant=self.kwargs['pk'], as well, but its the same result of zero. COunt_1 is totally working. I am just trying to capture of orders made by customers of a particular merchant within the last week. My model: class Order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, blank=True) #order_items = models.ManyToManyField('OrderItem',blank=True, null=True) order_status = models.CharField(max_length=50,choices=ORDER_STATUS,default='To_Ship') ordered_date = models.DateTimeField(auto_now_add=True) -
Let's Encrypt Certbot and Gunicorn
Certbot has this section in the beginning where I have to specify "My HTTP website is running **(web server) on **(system it's running on )" I use Google Domain for my domain and heroku to deploy. I'm using Django. After a bit of research I found out that my website is runing on a gunicorn webserver. In this case, which one should I select on the Software? They have Apache, Nginx, Haproxy, Plesk, Web hosting product, none of the above. Also How can I find out which system my webdite is runing on? Thank you in advance. Any advice is appreciated. I'm aware that if I upgrade my heroku to a padiu version it's easier but I want to do it for free. I got my account verrified. -
Why my django server is not down for seconds after adding changes? Before server used to stop for a while after adding changes
Before when I did some changes in my django files views.py or admin.y file in django, after refreshing browser server for 1-2 seconds is down and then starts working, but I don't know what changed now, when I add change to admin.py or other django files server is not stopping by itself automatically. It keeps running even if I add inappropriate syntax to the django files. After re-running server django detects changes. Why this happens? Before django could detect changes in its files without re-running but now I have to re-run server to see changes I am using PyCharm (latest version) Ubuntu 19.04 Chrome Python 3.7 Django 3.2.3 -
How to set a permanent value to a Django Form Field
I am building blogsite where authenticated user can add post. The form has three fields including 'user' field (which shows all the user list with a drop down option). The problem is authenticated user can also see other user name. I have tried two solution Exclude this field when rendering in template or whatever the username is chosen the post post will be saved by the name of authenticated user but the solution I want 'user' field will only show the name of authenticated user and that will be submitted with title and description class BlogForm(forms.ModelForm): class Meta: model = Blog fields = '__all__' ''' view function if fm.is_valid(): us = fm.cleaned_data['user'] ti = fm.cleaned_data['title'] ds = fm.cleaned_data['desc'] post = Blog(user=us, title=ti, desc=ds) messages.success(request, 'Blog Created') post.save() -
NoReverseMatch at /cart/ Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name
Error NoReverseMatch at /cart/ Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/cart/ Django Version: 3.2.3 Exception Type: NoReverseMatch Exception Value: Reverse for 'ProductView' not found. 'ProductView' is not a valid view function or pattern name. Error Screenshot This is where it shows me error, when I try to add a product to cart sessions,tho the product it added to cart sessions but when the url for cart-details is called, while loading the main base.html file it gives me a error that productView cannot be found ProductApp Templates 'app/base.html' <!doctype html> {% load static %} <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <base href="/"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Poppins:200,300,400,500,600,700,800&display=swap" type="text/css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lora:400,400i,700,700i&display=swap" type="text/css"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Amatic+SC:400,700&display=swap" type="text/css"> <!-- Bootstrap CSS --> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <!-- <link rel="stylesheet" href="{% static 'app/css/open-iconic-bootstrap.min.css' %}"> <link rel="stylesheet" href="{% static 'app/css/animate.css' %}"> --> <!--Owl Carousel CSS--> <link rel="stylesheet" href="{% static 'app/css/owl.theme.default.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/magnific-popup.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/aos.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/ionicons.min.css' %}" type="text/css"> <link rel="stylesheet" href="{% static 'app/css/bootstrap-datepicker.css' %}" type="text/css"> <link rel="stylesheet" href="{% … -
I am able to get else part of the code, Else part is not working
I am working on this code of logging in to the application. I can see that only if statement is working in this code for the valid values of username and password. If i enter the invalid values of username and password the else part should work, But it's not working. **main.py** @app.post("/loginsuccess/", response_class=HTMLResponse) async def login_success(request: Request, username: str = Form(...), password: str = Form(...)): p = await User_Pydantic.from_tortoise_orm(await User.get(username=username, password=password)) if p is not None: json_compatible_item_data = jsonable_encoder(p) print(json_compatible_item_data["username"], "22222222222222222") return templates.TemplateResponse("homepage.html", {"request": request, "username":username}) else: print("NOOOOOOOOOOOOOOOOO") status_code:int status_code = 500 return templates.TemplateResponse("index.html", {"request":request, "status_code":status_code}) -
Can anyone please explain what error is this, OSError [Errno 22] Invalid argument
I'm getting this error and I don't know how to solve it, i think this is related to templates directory. this is how my templates are stored My view -
Why am I not POSTing data to database Django/Python
I am unable to get the data to my database am I missing something. Followed a couple tutorials, tried my own tweaking but no luck thus far. I m not getting any errors but when I click submit on the form my database is not populating. My View def createUser(request): # form = UserForm() args = {} if request.method=='POST': userform = UserForm(request.POST) petform = PetForm(request.POST) if userform.is_valid() and petform.is_valid(): newuser = userform.save() newpet = petform.save(False) newpet.newuser = newuser newpet.save() return render(request, 'pet_list.html' ) else: userform = UserForm() petform = PetForm() args.update(csrf(request)) args['userform'] = userform args['petform'] = petform return render(request, 'add_user_pet.html', args) My Template <form action="/ " method="POST" > {% csrf_token %} <h3 class="details">User Info</h3> {{userform}} <h3 class="details">Pet Info</h3> {{petform}} <input type="submit"/> </form> Form.py class UserForm(forms.ModelForm): name = NameField() email = forms.CharField(label='E-mail',widget=forms.TextInput(attrs={"placeholder":"Whats your email"})) class Meta: model = User fields = ['name', 'email'] ################################################# class PetForm(forms.ModelForm): class Meta: model = Pet fields = [ 'name', 'submitter', 'species', 'breed', 'description', 'sex', 'age' ] -
Can we change invoice number when date change django
Please help me i am stuck in a problem if we have invoice number and we need to change according to financial year which is 1 april so can we change invoice no. Year for example - now is 2021 so invoive no. Is -- 210001 if it's 2022 invoice is 220001 so it is possible or not ???