Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Change password form or link in abstractuser django custom user model
I created a custom user model using abstractuser and replace mobile with username and then recreate user page in admin but my problem is I don't have change password form (in default Django authentication) and if I put save method and change other data in the user model then empty password stored and user can not login any more models.py: class MyUser(AbstractUser): username = None mobile = models.CharField(max_length=15, unique=True) international_id = models.CharField(max_length=25, blank=True, null=True) company_name = models.CharField(max_length=255, blank=True, null=True) business_code = models.CharField(max_length=25, blank=True, null=True) otp = models.PositiveIntegerField(blank=True, null=True) otp_create_time = models.DateTimeField(auto_now=True) objects = MyUserManager() USERNAME_FIELD = 'mobile' REQUIRED_FIELDS = [] backend = 'custom_login.mybackend.ModelBackend' admin.py: class MyUserAdmin(admin.ModelAdmin): list_display = ['mobile','company_name'] search_fields = ['mobile'] form = UserAdminChangeForm fieldsets = ( (None, {'fields': ('mobile','email','password','otp')}), ('Personal Info', {'fields': ('first_name', 'last_name','international_id')}), ('Company Info', {'fields': ('company_name','business_code')}), (_('Permissions'), {'fields': ('is_active', 'is_staff','is_superuser','groups','user_permissions')}), (_('Important dates'), {'fields': ('last_login', 'date_joined')}), ) class Meta: model = MyUser admin.site.register(MyUser,MyUserAdmin) forms.py: from django import forms from .models import MyUser from django.contrib.auth.forms import ReadOnlyPasswordHashField from django.utils.translation import ugettext as _ class UserAdminChangeForm(forms.ModelForm): """A form for updating users. Includes all the fields on the user, but replaces the password field with admin's password hash display field. """ # password = ReadOnlyPasswordHashField(label=("Password"), # help_text=("Raw passwords are not … -
virtualenv raises importerror because of changing app name in django
I've used [this link] to rename my django app. So I've edited some files and table's name and so on. But as it has been mentioned in that link, There is problem with virtualenv. So how can I fix it? I've change name "notes" to "blog". -
Django - divert all messages running in a Google Cloud Engine Instance into a file
How can I divert all messages of a Django application that runs in a Google Cloud Engine instance into a file ? This is my current settings for the logging options : LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.FileHandler', 'filename': '/tmp/mylogs.log', }, }, 'loggers': { 'django': { 'handlers': ['file'], 'level': 'DEBUG', 'propagate': True, }, }, } It provides output (which are created with logging functions) to some extend, however when there is a stack trace and exception. It does not provide the output into the file. This is how I execute Django on the console : python3 manage.py runserver --noreload >> /tmp/mylogs.log -
HTML changes not reflecting in Django
I am new to Django and have started a project but I am facing an issue. All my pages are working fine and the changes I make are getting reflected on the webpage but when I make a changes to my login page, no changes are reflected on the webpage (It is a simple static page, I only used Django template and nothing else). I deleted all the content in the html file and even deleted the whole html file but no error or change was shown and the page loaded just the way it was when first created. I also tried pressing Shift+F5 but nothing worked :( The output in terminal was as follows (even after deleting the file): [25/Jun/2021 10:24:23] "GET /login HTTP/1.1" 200 8183 -
I am currently using DRF token based authentication where i want to give a role to the user of either a mentor or the student, how to achieve that?
serializers.py for authentication from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password') views.py for authentication from rest_framework import serializers from rest_framework_jwt.settings import api_settings from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username',) class UserSerializerWithToken(serializers.ModelSerializer): token = serializers.SerializerMethodField() password = serializers.CharField(write_only=True) def get_token(self, obj): jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER payload = jwt_payload_handler(obj) token = jwt_encode_handler(payload) return token def create(self, validated_data): password = validated_data.pop('password', None) instance = self.Meta.model(**validated_data) if password is not None: instance.set_password(password) instance.save() return instance class Meta: model = User fields = ('token', 'username', 'password') models.py class NormalUser(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) name = models.CharField(max_length=30) email = … -
Local Development Server Errors
Exception happened during processing of request from ('127.0.0.1', 56261) Traceback (most recent call last): File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 650, in process_request_thread self.finish_request(request, client_address) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socketserver.py", line 720, in init self.handle() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 174, in handle self.handle_one_request() File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\site-packages\django\core\servers\basehttp.py", line 182, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "C:\Users\Name\AppData\Local\Programs\Python\Python38\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) ConnectionAbortedError: [WinError 10053] An established connection was aborted by the software in your host machine -
My pipenv is not recognized whenever i try to create a virtual environment, how do i solve this?
I've installed pipenv on my terminal, however whenever I try to start pipenv shell to create a virtual environment this error shows up "pipenv : The term 'pipenv' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:1 + pipenv shell + ~~~~~~ + CategoryInfo : ObjectNotFound: (pipenv:Strin g) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException" what is wrong and how do I get around it? -
how to get dropdown selected value and not text while submitting form in django views?
i have a dropdown list which you can see on left side. i want to fetch the value of dropdown in my views.py but when i cleaned_data['city'] it gives me the text of the selected value and not the value . how can i get this? can anyone help me models.py from django.db import models from .validator import validate_age # Create your models here. class City(models.Model): city_name=models.CharField(max_length=200) def __str__(self): return self.city_name class Employee(models.Model): name = models.CharField(max_length=200) pan_number = models.CharField(max_length=200, unique=True, null=False, blank=False) age = models.IntegerField(validators=[validate_age]) gender = models.CharField(max_length=10) email = models.EmailField() city = models.ForeignKey(City, on_delete=models.DO_NOTHING) def __str__(self): return self.name def clean(self): if self.name: self.name =self.name.strip() views.py def employee(request): context = {} if request.POST: form = EmployeeForm(request.POST) if form.is_valid(): name = form.cleaned_data['name'] pan_number = form.cleaned_data['pan_number'] email = form.cleaned_data['email'] age = form.cleaned_data['age'] city = form.cleaned_data['city'] gender = form.cleaned_data['gender'] print(city) with connection.cursor() as cursor: cursor.callproc('insert_employee', [name, pan_number, age, gender, email, city]) # qs_add = Employee(name=name, pan_number=pan_number, email=email, age=age, city=city, gender=gender) # qs_add.save() messages.add_message(request, messages.INFO, 'Employee save successfully') context['form'] = context['form'] = EmployeeForm() else: context['form'] = EmployeeForm(request.POST) else: context['form'] = EmployeeForm() return render(request, 'app/employee.html', context) -
How to insert into multiple postgres tables connected with foreign keys in Django ORM
I want to insert into two tables one table is Invoices other one is products. Invoice table connected to product table with product_id fk. A invoice can have multiple products at the same time and invoice detail and product details shall be insert at the same time (there is no existing product on products table) so I have to models: class Invoice(models.Model): ... product = model.Foreignkey (products, releted_name="invoice_product", on_delete=models.CASCADE) ... class Products(models.Model): id = models.Charfield() name = models.Charfield() ... -
How to set date limit to a user for a particular package in Django
I have a model named as Plans which is independent of user but when user buys a plan it stored in UserPlanSubscription model so problem is when user buys particular plan user will get that plan for a Month, Year or 6 Month so I want to set expiry of that plan for example if I buyed a Plan for 6 Month so it should expire after 6 Month how can I do this. this is my UserPlanSubscription model class UserPlanSubscription(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE,null=True,blank=True) plan = models.ForeignKey(Plans, on_delete=models.CASCADE,null=True,blank=True) paid = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now=False, auto_now_add=True, null=True) expiry_date = models.DateTimeField(auto_now=False, auto_now_add=False,null=True) and this is my Plans model class Plans(models.Model): user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) plan_name = models.CharField(max_length=255, null=True) plan_note = models.CharField(max_length=255, null=True) plan_price = models.CharField(max_length=255, null=True) access_to = models.ManyToManyField(Add_e_office) -
i am getting multivaluedictkeyerror while getting values from the form
i wanted some details to update in user details model but when i try to read valued in th request it show the multivaluedictkeyerror. error image error image 1, error image 2 views.py @csrf_exempt def updateuser(request): myuser=request.user obj=User.objects.get(id=myuser.id) if request.method == 'POST': p=request.POST['phone'] a=request.POST['add'] e=request.POST['edu'] em=request.POST['email'] c=request.POST['country'] s=request.POST['state'] userdetails.objects.create(user=obj,phone=p,address=a,edu=e,country=c,state=s) return render(request,'profile.html') html code <form action="updateuser" method="POST"> {% csrf_token %} <div class="row mt-3"> <div class="col-md-12"><label class="labels">PhoneNumber</label><input type="tel" class="form-control" placeholder={{uobj1.phone}} name="phone" required></div> <div class="col-md-12"><label class="labels">Address</label><input type="text" class="form-control" placeholder={{uobj1.address}} name="add" required></div> <div class="col-md-12"><label class="labels">Email ID</label><input type="email" class="form-control" placeholder={{uobj.email}} name="email" ></div> <div class="col-md-12"><label class="labels">Education</label><input type="text" class="form-control" placeholder={{uobj1.edu}} name="edu" required></div> </div> <div class="row mt-3"> <div class="col-md-6"><label class="labels">Country</label><input type="text" class="form-control" placeholder={{uobj1.country}} name="country" required></div> <div class="col-md-6"><label class="labels">State/Region</label><input type="text" class="form-control" value="" placeholder={{uobj1.state}} name="state" required></div> </div> <div class="mt-5 text-center"><button class="btn btn-primary profile-button" type="submit">Save Profile</button></div> </form> -
Page not found (404) on django
I am using django 3.2 to build a personal e-commerce project, Got Error-Page not found (404) on visiting my products page url Method:GET URL:http://127.0.0.1:8000/products Using the URLconf defined in main.urls. I have followed all the conventions and the other pages are all working but this one is giving me a[urls[\views][1][browser display] hard time as i feel everything is correct, i might be wrong, pls help and if u need to see more of my code, please let me know. This is my code for urls from django.urls import path from django.views.generic.detail import DetailView from django.views.generic import * from main import models, views app_name = 'main' urlpatterns = [ path('', views.home, name='home'), path('about_us/', views.about_us, name='about_us'), path('contact-us/', views.ContactUsView.as_view(), name='contact_us'), path( "products/<slug:tag>/", views.ProductListView.as_view(), name="products" ), path("product/<slug:slug>/", DetailView.as_view(model=models.Product), name='product'), ] my code for views from django.views.generic.edit import FormView from .forms import ContactForm from django.views.generic.list import ListView from django.views.generic.detail import DetailView from django.shortcuts import get_object_or_404 from main import models class ProductListView(ListView): template_name = "main/product_list.html" paginate_by = 4 def get_queryset(self): tag = self.kwargs['tag'] self.tag = None if tag != "all": self.tag = get_object_or_404( models.ProductTag, slug=tag ) if self.tag: products = models.Product.objects.active().filter( tags=self.tag ) else: products = models.Product.objects.active() return products.order_by("name") then my browser Page not found (404) … -
when I try to run my django server I get an error
The error is django.core.exceptions.ImproperlyConfigured: Application labels aren't unique, duplicates: something apparently I have 2 applications that are the same but I don't I checked. Not sure how to fix this. -
How to get form values in template before submit the form?
I created a form with Django. In this form I have a filefield. How can I find out if the user has filled in this field before the form is submitted? I want to pop up a warning screen if the file didn't load like "Are you sure?". How can I do that? This is an example form: <form method="post" enctype="multipart/form-data" > {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-warning">Submitbutton> </form> **model: ** class Pdf(models.Model): id = models.AutoField(primary_key=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to=customer_directory_path, null=True, blank=True) document_type = models.CharField(max_length=200, default='Select', choices=CHOICES) ... -
How to Display Category name of Product in Django?
I have a relation between category, subcategory, and sub-child category, and the product is related to the sub-child category, but I want to display the name of Category. Please let me know how I can do it. here is my models.py file... class Category(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) class SubCategory(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) category = models.ForeignKey('Category', related_name='subcategoryies', on_delete=models.CASCADE, blank=True, null=True) class SubChildCategory(models.Model): subcategory=models.ForeignKey(SubCategory, related_name='SubChildRelated', on_delete=models.CASCADE, default=None, verbose_name='Sub Category') name=models.CharField(max_length=50, default=None) slug=models.SlugField(unique=True, max_length=50) here is my product models.py file... class Product(models.Model): name=models.CharField(max_length=225) slug=models.SlugField(max_length=225, unique=True) subcategory=models.ManyToManyField(SubChildCategory, related_name='pro_subchild', verbose_name='Select Category') here is my views.py file... def home(request): allProds=[] catprods= Product.objects.values('subcategory__subcategory__category', 'slug') cats= {item["subcategory__subcategory__category"] for item in catprods} for cat in cats: prod=Product.objects.filter(subcategory__subcategory__category=cat) n = len(prod) nSlides = n // 10 + math.ceil((n / 10) - (n // 10)) allProds.append([prod, range(1, nSlides), nSlides]) return render(request, 'main/index.html',{'allProds':allProds} here is my index.html file... {% for product, range, nSlides in allProds %} <div class="section small_pt pb-0"> <div class="custom-container"> <div class="row"> <div class="col-xl-3 d-none d-xl-block"> <div class="sale-banner"> <a class="hover_effect1" href="javascript:void()"> <img src="{% static 'front/assets/images/shop_banner_img6.jpg' %}" alt="shop_banner_img6"> </a> </div> </div> <div class="col-xl-9"> <div class="row"> <div class="col-12"> <div class="heading_tab_header"> <div class="heading_s2"> <h4>{{product.subcategory.SubChildRelated.subcategoryies.name}}</h4> </div> <div class="view_all"> <a href="{{obj.cat_slug}}" class="text_default"><i class="linearicons-power"></i> <span>View All</span></a> </div> </div> </div> </div> <div class="row"> <div class="col-12"> <div class="tab_slider"> … -
My point annotation in Chart.js 3.3.2 won't render in my Django template. Making a realtime graph of temperature for my wood-fired pizza oven
The goal and problem: I'm having trouble getting an annotation to render in Chart.js. My project is a Django/Chart.js-run graph that shows the temperature of my wood fire pizza oven. I would like to see the temperature graphed over time and be able to submit a model form indicating when I have shut the door, and to have that annotated on the graph. Specific issue The issue is that I can't get the annotation to render on my graph, partly because I am unsure what x/y coordinate to put in. This can be seen in the const options variable in my index.html. In order, have attached my base.html, index.html, view.py, and forms.py. I also included a link to a screen shot of the graph so far and of my pizza oven in case you're curious. :P Versions I'm using Python 3.9.5, Chartjs 3.3.2, and Django 3.2.4. Would be grateful for some help! -Mike <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="styles.css"> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <!--Chartjs CDN--> <!--<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4/dist/Chart.min.js"></script>--> <script src="https://cdn.jsdelivr.net/npm/chart.js"></script> <title>{% block title %}{% endblock %}</title> </head> <body> {% block content %} {% … -
How do I exclude values based on one model's queryset to in another model
I'm having two models, bike and BikeRentHistory. All I want to do is I want to search for the bikes which are available and not on rent on selected from_date, from_time, to_date, and to_time. I'm trying to filter all the bikes' IDs from the BikeRentHistory model which are on rent on the selected from date and time, to date and time and then excluding those IDs from the bike model so that I can get available bikes. Can anyone help me on how do I filter in this? models.py class bike(models.Model): BIKE_STATUS_CHOICES = [('A', 'Available'), ('R', 'On Rent')] operatorid = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True, help_text='Enter operator id') bikename = models.CharField(max_length=50, help_text='Enter bike name', verbose_name='Name of Bike') brandname = models.CharField(max_length=50, help_text='Enter bike brand name', verbose_name='Brand Name') price_hr = models.IntegerField(help_text='Enter bike price per hour', verbose_name='Price Per Hour') price_day = models.IntegerField(help_text='Enter bike price per day', null=True, verbose_name='Price Per Day') registered_no = models.CharField(max_length=50, help_text='Enter bike registered number', verbose_name='Bike Registration Number') bike_image=models.ImageField(upload_to='bike_image', help_text='Add bike image', null=True) bike_manufactured_date=models.DateField(help_text='Add Manufactured date of bike') bikecolor = models.CharField(max_length=50, help_text='Enter bike color', verbose_name='Bike Color') bikestatus = models.CharField(choices=BIKE_STATUS_CHOICES, max_length=1, default='A', verbose_name='Select Bike Status') station_id = models.ForeignKey(Station, on_delete=models.CASCADE, verbose_name='Select Station Location') class BikeRentHistory(models.Model): customer = models.ForeignKey(Customer, on_delete=models.PROTECT, null=True, related_name='customer+') operator = models.ForeignKey(Customer, on_delete=models.PROTECT, … -
Django and Linux users
I'll send it through the translator, so I'm sorry for the mistakes ;) I have a webservice ( nginx gunicorn dhango). I connected django users and linux users using django_pam . Now I need to create a widget in the admin panel that will allow me to create new users. But the widget must also create a user in the operating system . The web service does not have a sudo. What should I do ? P.s. I can't get away from such a trick-the production of the authorities -
How to validate email before send mail and finding whether the mail send - django
I use - is_valid = validate_email(e) for validating email. It can detect if @ is not present or some more but not providing whether the email entered is active now. AND I used sendmail for sending email. I used try except block. Mail is sending but sometimes try code running and someother times except block is running. How to avoid this abnormal behaviour. -
Validating uploaded csv file with django forms
I've just created a simple admin template with such a form: class UploadProductForm(forms.Form): file = forms.FileField(widget=forms.FileInput(attrs={"accept": ".csv"})) Here is how it works: def open_upload_form(self, request): user = request.user if not user.is_superuser: return redirect(reverse("admin:index")) if request.method == "POST": form = UploadProductForm(request.POST, request.FILES) if form.is_valid(): self.generate_objects_from_csv(request.FILES["file"]) [...] else: form = UploadProductForm() context = {"form": form} [...] def generate_objects_from_csv(self, uploaded_file: InMemoryUploadedFile): dataframe = pd.read_csv(uploaded_file, index_col=0) df_records = dataframe.to_dict("records") model_instances = tuple(self.model(**record).to_mongo() for record in df_records) try: self.model._get_collection()\ .insert_many(model_instances, ordered=False) except BulkWriteError: pass Well... Users have a possibility to get the CSV's template to fill it but everyone knows that there's a possibility to change something - the column name or type or whatever and then they'll get a 500 error instead of the Django admin's error. Any ideas on how to make a validation? I would like to achieve this by using a self.model's clean() method or something similar. -
Allow HTML characters in Django Rest Framework serializers
I am returning HTML text from Django Rest Framework, but special characters are rewritten as "HTML safe" text. How do I prevent this behaviour? I know there is a mark_safe() function in Django, but that would require me to rewrite the serializer. Is there an easy way to do this offered by DRF? Here is my serializer: class MySerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = ("html_text",) Note that the text is safe and only input by admins, not by end users. -
TemplateSyntaxError at GET in Django template
I'm working on Django template and setting Conditional branching whether there is a "query" or not. {% if {{ request.GET.query }} == "" %} <td><a href="/detail/{{item.id}}/{{item.item_hs6}}">detail</a></td> {% else %} <td><a href="/detail/{{item.id}}/{{item.item_hs6}}/{{ request.GET.query }}">detail</a></td> {% endif %} When I execute the above code, the error occurs here. Exception Type: TemplateSyntaxError Exception Value: Could not parse the remainder: '{{' from '{{' I know the code below is something wrong {% if {{ request.GET.query }} == "" %} How should I judge whether there is a query or not in Template? I just mentioned the above settings in this question but still if more code is required then tell me I'll update my question with that information. Thank you -
Why my form shows a blank date field to be filled manually, instead of providing me a calendar to choose a specific date?
I created a model which has two date fields. When I use the form in the admin panel, I get to choose the dates from the attached calendar, but when I render the same form on the web-page, it gives me a blank field. There is no calendar. Below are my codes: models.py: from django.db import models from django.core.validators import RegexValidator from django.db.models.deletion import CASCADE # Create your models here. class Diagnosis(models.Model): diagnosis=models.CharField(max_length=30, blank=True) class InitialData(models.Model): pattern = RegexValidator(r'RT\/[0-9]{4}\/[0-9]{2}\/[0-9]{4}', 'Enter RT Number properly!') pattern1 = RegexValidator(r'OOPL\/D\/00[0-9]', 'Enter Case Number properly!') case_number=models.CharField(max_length=10, primary_key=True, unique=True, validators=[pattern1], blank=True) date_of_admission=models.DateField(default=None) date_of_discharge=models.DateField(default=None) name=models.CharField(max_length=100, default=None) mr_uid=models.IntegerField(default=None) rt_number=models.CharField(max_length=15, blank=False, validators=[pattern], default=None) diagnosis=models.ForeignKey(Diagnosis, on_delete=CASCADE) forms.py: class TrackReportForm(ModelForm): class Meta: model=InitialData fields=('case_number', 'date_of_admission', 'date_of_discharge', 'name', 'mr_uid', 'rt_number', 'diagnosis') class DiagnosisForm(ModelForm): class Meta: model=Diagnosis fields=('diagnosis',) views.py: def initialview(request): if request.method=='POST': fm_diagnosis=DiagnosisForm(request.POST) fm_initialdata=TrackReportForm(request.POST) if fm_diagnosis.is_valid() and fm_initialdata.is_valid: diagnosis=fm_diagnosis.save() initial=fm_initialdata.save(False) initial.diagnosis=diagnosis initial.save() fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) else: fm_diagnosis=DiagnosisForm() fm_initialdata=TrackReportForm() return render(request, 'account/database.html', {'form1':fm_diagnosis, 'form2':fm_initialdata}) URLs: from account import views urlpatterns = [ path('admin/', admin.site.urls), path('data/', views.initialview), ] template: <body> <form action="" method="post" novalidate> {% csrf_token %} {{form1.as_p}} {{form2.as_p}} <button type="submit">Save</button> </form> </body> Any suggestions? -
django upload files using class based view
I am facing this problem when I try to upload files it doesn't work from the html page but from the admin panel it works. my model is: class contrat(models.Model): contrtID = models.CharField(max_length=25,unique=True) SHRPath = models.FileField(upload_to='contrats/') post_date = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User,on_delete=models.CASCADE) def __str__(self): return self.contrtID def delete(self, *args, **kwargs): self.SHRPath.delete() super().delete(*args, **kwargs) def get_absolute_url(self): return reverse('Scheduling') class Meta: ordering = ('-post_date',) The form is: class contrat_F(forms.ModelForm): contrtID = forms.CharField(label='Code',max_length=25) class Meta: model= contrat fields=('contrtID','SHRPath') The Views.py is: class Contratadd(LoginRequiredMixin, CreateView): model = contrat template_name = 'Home/Scheduling/Add_contract.html' form_class= contrat_F def form_valid(self, form): form =contrat_F(request.POST, request.FILES) form.instance.author = self.request.user return super().form_valid(form) the urls.py is: path('Add_Contrat/', views.Contratadd.as_view(), name='Add_Contrat'), the page html code is: <form method="POST"> {% csrf_token %} <div class="border p-2 mb-3 mt-3 border-secondary"> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{ form.contrtID|as_crispy_field }} </div> <div class="form-row"> <div class="form-group col-md-12 mb-0"> {{form.SHRPath}} </div> </div> </div> <input class="btn btn-success mb-4" type="submit" value="ADD Contrat"> </form> THIS IS IN THE PAGE BUT IT DOESN'T UPLOAD THE FILE! where is my mistake please? -
Different number of columns needed for last page of paginated Django template
My question concerns needing to style the last page of a paginated Django template so that it displays as only one column if there are fewer than the maximum 6 entries on the page (the other pages of the template are displaying in two columns). I am using Django 3.1.7 I have a Django template that uses the following view: Django View: class SoundSeedView(generic.ListView): model = SoundFile fields = ['sound_file'] template_name = 'seed_history.html' paginate_by = 6 I am using two columns on my template as given below: CSS: #columns { columns: 2; } Django template: <h1>Sound file list</h1> <button id="comments-button" onclick="displayComments()">View Comments</button> <div id="blackbackground"> </div> <div class="container" id="columns"> {% for document in object_list%} <div id= "entryContainer"> <h2 id = 'ttitle'> {{ document.sound_file.name }} </h2> <p> Created on: {{ document.created_on}} </p> <div id = "nameTrunc"> <p> Created by: {{ document.user }} </p> </div> <div id="nc" class = "new-comments"> <audio controls class="thisAudio" id="player"> <source src="{{ document.sound_file.url }}"> </audio> {% if user.is_authenticated %} <a id = 'downloadbutton' class = 'dwnld-button' href="{{ document.sound_file.url }}" download >Download</a> {% endif %} <p class = "comments-text"> Comments: {{ document.comments }}</p> </div> </div> {% endfor %} </div> My problem is that if there are fewer than the maximum …