Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Displaying selected by checkboxes columns of table
I have a table with 60 columns and I want to make a selection by columns, using checkboxes. How can I display selected by checkboxes columns of table? -
Django form with multiple checkboxes
I am really new to Django! I have a page that displays items with checkboxes next to them. The number of items/checkboxes varies. When a button is pressed, I want the corresponding checked item to be modified. So far, I have tried to wrap it all in one form: <form method="post"> {% csrf_token %} {% for event in items %} {{ event.eventID }} <input type="checkbox" value="{{ event.eventID }}" name="choices"> {% endfor %} <button type="submit">Approve</button> </form> I want to collect them in a Django form field. I am trying to use ModelMultipleChoiceField: class ApproveEventForm(forms.Form): choices = forms.ModelMultipleChoiceField(queryset = Event.objects.all(), widget=forms.CheckboxSelectMultiple()) And in my views, I want to edit the selected items: def approve_event(request): if request.method == "POST": form = ApproveEventForm(request.POST) print(form.errors) if form.is_valid(): for item in form.cleaned_data['choices']: item.approved = True item.save() else: form = ApproveEventForm() unapproved = Event.objects.filter(approved=False) return render(request, 'app/approve_event.html', {'items': unapproved}) My form is not valid and form.errors prints: choices "" is not a valid value for a primary key. How can I fix this? Or is there another way to access the selected items? -
Class Based FormView
I have researched this issue for a couple of days and can't seem to find what I'm looking for exactly. I have searched ModelChoiceField as well as ChoiceField on StackOverflow as well as Google and there are many variations of my question but nothing exactly. In a nutshell, I am trying to use a Class Based FormView and then capture the user selection and pass it to a Class Based ListView. Here is my code. Forms.Py class BookByStatus(forms.Form): dropdown = forms.ChoiceField(choices=[],required=False) def __init__(self, user, *args, **kwargs): super(BookByStatus, self).__init__(*args, **kwargs) self.fields['dropdown'].widget.attrs['class'] = 'choices1' self.fields['dropdown'].empty_label = '' self.fields['dropdown'].choices = Book.objects.values_list("author","author").distinct("Publisher") The code above works fine, and shows me the output I'm looking for on my view. No issues there....Then I have my FormView... class BookByStatusView(LoginRequiredMixin,FormView): model = Book form_class = BookByStatus template_name = 'xyz123/publisher.html' success_url = reverse_lazy('Book:book_by_list') def get_form_kwargs(self): kwargs = super(BookByStatusView, self).get_form_kwargs() kwargs['user'] = self.request.user return kwargs def form_valid(self, form): BookByStatusView = form.cleaned_data['dropdown'] return HttpResponseRedirect(BookByStatusView.get_absolute_url1()) The code above works fine, but takes me to the ListView below which I can't seem to pass the dropdown value to....I've tried several different iterations of get_form_kwargs as well as changed my form to ModelChoiceField, but still can't seem to understand how to get a … -
Serverless and NewRelic
I'm using the latest version of the Serverless framework and am trying to integrate NewRelic into my applications. I have both Django as well as Flask applications (-> Python!) which I'd like to monitor with NewRelic. I integrated the framework as documented (by wrapping the WSGI application) and set the NewRelic timeout variables accordingly to make sure data is getting sent. In my NewRelic dashboard I'm able to see the project but no data is reported. Has anyone had success getting this running? Thanks! -
django the way to access data from input form
The title looks cliche, but I didn't find the solution that fits in my situation :( My symptom is when I click the modify button and then I write down the information on new window that is implemented by bootstrap div part. However, my database doesn't change at all. Please ignore ... in codes, I delete attributes that looks messy. Codes can have typo, because I wrote it down manually to find a bug, but I didn't find :( I tried in view.py, address_modify makes return Httpresponse(street), but It returned None. That is what I have been stuck in for days. I appreciate! Best view.py def address_modify(request, adid): cat = get_object_or_404(Address, adid=adid) if request.method == "POST": old_adid = adid email = request.user.email street = request.POST.get("street", None) city = request.POST.get("city", None) ... Address.objects.filter(adid=adid).update(..., street=street, city=city, state=state, ...) return redirect('/address/') return redirect('/address/') template ( I name it address.html) <button class="btn btn-success" data-toggle="modal" data-target="#modify">MODIFY</button> <div class ="model fade" id="modify" role="dialog"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <from action="" method="POST">{% csrf_token %} </div> <div class="modal-body"> <input type="text" name="street"> <input type="text" name="city"> ... ... <input type="text" name="zipcode"> </div> <div class="modal-footer"> <a href="{% url 'address_modify' i.adid %}">{% csrf_token %} <button type="button" class="btn btn-primary">Save Change</button></a> <div></form> urls.py … -
ValueError at /author/admin/ in Django
I have the following blog project : urls.py conf : url(r'^author/(?P<author>\w+)/$', views.getAllPosts, name='grabAuthorPosts') posts/models: class Post(models.Model): title = models.CharField(max_length=200) summary = models.CharField(max_length=500, default = True) body = models.TextField() pub_date = models.DateTimeField(default=timezone.now) category = models.ManyToManyField('Category') author = models.ForeignKey(User, default=True) slug = models.SlugField(max_length=100, unique=True, blank=True) def __str__(self): return self.title def slug(self): return slugify(self.title) posts/views: def getAllPosts(request, author=False): latest_posts = Post.objects.all().order_by('-pub_date') comments = Comment.objects.all().order_by('-pub_date') author_posts = latest_posts.filter(author=author) context = { 'latest_posts':latest_posts, 'comments':comments, 'author_posts':author_posts } return render(request, 'posts/getAllPosts.html', context) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(max_length=500, blank=True) location = models.CharField(max_length=30, blank=True) birth_date = models.DateField(null=True, blank=True) templates/posts/getAllPosts: <a href={% url 'grabAuthorPosts' author=post.author.username%}> {{post.author}}</a> I am trying to make it so that when the post.author link is clicked, the user will be taken to a page consisting of posts related to that particular author. The link formulation itself seems ok, as when clicked on a post created by admin, the url reads : "localhost/author/admin/ I believe my problem is in getting the context variable author_posts to work. I'm new to Django so any explanation greatly appreciated. latest_posts, as well as author=False is used elsewhere in the template to get all posts regardless of author, which works fine. The error is : ValueError at /author/admin/ … -
How to retrieve additional JSON data from request in django ModelSerializer
I have a model serializer that creates a Program object, along with another OutboundProgram object. The json I receive has all the details of a program object and the additional ones I need to create the OutboundProgram. How do I retrieve the additional fields because serializer only reads the fields for a certain object. P.S. our team lead doesnt want me to use a nested JSON json received by the request: { "linkage": "AP", "name": "something", "academic_year": 2017, "terms_available":[1,2], "is_graduate": false, "requirement_deadline":"2011-10-16", "institution": 3 } models.py class Program(SoftDeletionModel): linkage = ForeignKey(Linkage) name = CharField(max_length=64) academic_year = ForeignKey(AcademicYear) terms_available = ManyToManyField(Term) is_graduate = BooleanField() def __str__(self): return self.name class OutboundProgram(SoftDeletionModel): program = ForeignKey(Program) requirement_deadline = DateField() institution = ForeignKey(Institution) serializers.py class OutboundProgramSerializer(ModelSerializer): class Meta: model = Program fields = "__all__" def create(self, validated_data): terms = validated_data.pop('terms_available') program = Program.objects.create(**validated_data) for term in terms: program.terms_available.add(term) program.save() print(validated_data) return program Any kind of help would be useful. Thanks! -
Django rest HyperlinkedModelSerializer with nested custom field
I have my model as follows class Asset(models.Model): name = models.CharField(('name'), max_length=50, blank=True) manufacturer = models.CharField(('manufacturer'), max_length=100, blank=True) address = models.CharField(('address'), max_length=100) owner = models.ForeignKey(User,on_delete=models.CASCADE) class Lease(models.Model): OPEN = 'OPEN' APPROVED = 'APPROVED' CLOSEREQUESTED = 'CLOSEREQUESTED' RENEWREQUESTED = 'RENEWREQUESTED' CLOSED = 'CLOSED' REJECTED = 'REJECTED' STATUS_CHOICES = ( (OPEN,'OPEN'), (APPROVED, 'APPROVED'), (CLOSEREQUESTED, 'CLOSEREQUESTED'), (RENEWREQUESTED, 'RENEWREQUESTED'), (CLOSED,'CLOSED'), (REJECTED, 'REJECTED'), ) user = models.ForeignKey(User, related_name='user',on_delete=models.CASCADE) asset = models.ForeignKey(Asset,related_name='asset',on_delete=models.CASCADE) start_date = models.DateField(auto_now=False) end_date = models.DateField(auto_now=False) status = models.CharField(choices=STATUS_CHOICES,default=OPEN,max_length=20) How can I write a serializer for Lease model so that I will be able to create new lease resource if I am sending the ids only for the user and asset fields. I have written a serializer as below but it is not getting created for the json payload below. class LeaseSerializer(serializers.HyperlinkedModelSerializer): class Meta: asset = serializers.StringRelatedField(source='assetId',) user = serializers.Field(source='lesseeId') model = Lease fields = ('assetId','startDate','endDate','lesseeId') Payload { "assetId":"", "startDate":"", "endDate":"", "lesseeId":"" } Do I need to create custom serializer in this case ? -
djangrestframework to display model in foreign key
Please excuse the title. Im not quite sure how ask this question without just showing. In django I have two models. class people(models.Model): name=models.TextField(max_length=100) nickname=models.TextField(max_length=100) class visits(models.Model): person=models.OneToOneField(people) visitdate=models.DateTimeField(auto_now=True) and then a serializer for the restapi. #serializers.py class VisitsSerializer(serializers.ModelSerializer): class Meta: model = visits fields=("id","person","date") When the API returns the dictionary, it looks like this. {id:1,person:1,visitdate:11/23/17} Is there a way to make the API return the actual values that are associated with the person with id 1? like so. {id:1,person:{id:1,name:foo,nickname:bar},visitdate:11/23/17} -
When should you use redirect instead of just calling the target view function directly?
Sometimes views need to make decisions about workflow and direct to different areas. For example def view_switchboard(request): if request.POST['data'] == 'option A': return redirect('Appname:viewA') elif request.POST['data'] == 'option B': return redirect('Appname:viewB') else: # in third case, we just need to do some speciailised actions also done elsewhere, for DRY we put it all in one place - actionC return redirect('Appname:actionC_as_view') However, the following is also possible: def view_switchboard(request): if request.POST['data'] == 'option A': return view_viewA(request) elif request.POST['data'] == 'option B': return view_viewB(request) else: result = actionC(request) context = do_more_processing(result) return render('switchboard_template',context) In fact, wouldn't the second option always be possible negating the need for redirect function all together? How inefficient is redirect? What is the right circumstance and wrong circumstances for using redirect? Any other tips for handling workflows of views? -
Creating multiple wagtail home pages
How do I create multiple static pages in wagtail such as home, about, contact, ectetera which are dependent upon the domain - not subdomain. I found the docs non-intuitive do I simply create a Page in admin under the root page such as Domain1HomePAge, Domain2HomePage, etcetera and set the root page under the sites in wagtail admint o point to this root page? -
Django form posts data with no errors, but does not register as 'is_valid'
I am creating my first Django form and I can see the data passing successfully to the console through my logging, but it does not save to the database because the post data is not registering as 'is_valid'. I would love to know why. Template - newpost.html <form method='POST' action=''>{% csrf_token %} {{newPost.as_p}} <input type='submit' value='Create Post'> </form> Form - forms.py class PostEntry(forms.ModelForm): class Meta: model = Entry fields = [ "image", "body", "user", "slug", "publish" ] Model - models.py class Entry(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) image = models.ImageField(upload_to="") body = models.TextField() slug = models.CharField(max_length=6, unique=True, default=rand_slug()) publish = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) def __str__(self): return self.slug def get_absolute_url(self): return '/posts/%s/%s' % (self.user, self.slug) class Meta: verbose_name = "Entry" verbose_name_plural = "Entries" ordering = ["-created"] View - views.py def NewJournalDetail(request): newPost = PostEntry() if request.method == "POST": print(request.POST.get("body")) # successful print(request.POST.get("image")) # successful print(request.POST.get("slug")) # successful print(request.POST.get("user")) # successful print(request.POST.get("publish")) # successful if newPost.is_valid(): # NOT successful print(newPost) instance = newPost.save(commit=False) instance.save() else: print('not valid') print(newPost.errors) # NO errors context = { "newPost": newPost, } return render(request, "newpost.html", context) Console Output [23/Nov/2017 10:19:51] "GET /create/ HTTP/1.1" 200 894 this is text from the body image.PNG 1FP2is 1 … -
Wagtail Migration error when removing Streamfield block
I had a Streamfield block based on SnippetChooserBlock which I removed, which was fine, migrations were fine. ('call_to_action_snippet', SnippetChooserBlock(CallToActionSnippet,icon="success",template='myapp/blocks/cta_snippet.html')), When I then tried to then also remove the CallToActionSnippet from my models, I get an error when running makemigrations from an older migration file: AttributeError: 'module' object has no attribute 'CallToActionSnippet' Any ideas what I'm doing wrong here? I know SF custom blocks can't be removed if they're based on certain block types but I thought a SnippetChooserBlock would be ok. thanks Joss -
Count Object in Models Django
I have a problem with creating a modelfield which Count number of people who like an article. I have class Like: class Reaction(models.Model): user = models.ForeignKey(User) article = models.IntegerField(null=True, blank=True) date = models.DateTimeField(auto_now_add=True, null=True) and class Article: from api.reactions.models import Reaction class Article(models.Model): user = models.ForeignKey(User) post = models.TextField() likes = models.IntegerField(default=0) def __str__(self): return self.post def calculate_likes(self): likes = Reaction.objects.count(article=self.pk) self.likes = likes self.save() return self.likes But likes wont be counted. What's wrong with this? Please help me. Thanks! -
Django: strange reverse match
In my app, I've got a view which generates a form. When this form is valid the view redirect to another view which is another form, but I have an error message with the reverse match. My views.py: def uploadData(request, dataType, method): if method == 'single': if dataType == 'Sequence-has-SNP': if request.method == 'POST': form = SeqHasSnpForm(request.POST) if form.is_valid(): idSequence = form.cleaned_data['seq_linked'] return redirect('addSNPsSeq', idSequence) else: form = SeqHasSnpForm() return render(request, 'myapp/upload_sequence-has-snp.html', locals()) else: ... else: ... def uploadSNPsToSeq(request, idSequence): seq = Sequence.objects.get(PK_idSequence = idSequence) thisSeqHasSnp = Seq_has_SNP.objects.filter(FK_idSequence = seq.PK_idSequence) snpAll = SNP.objects.all() if request.method == 'POST': form = SelectSNPsForSeqForm(request.POST, snps=snpAll, seqHasSnps=thisSeqHasSnp) if form.is_valid(): print('Yeaaahhh!') else: form = SelectSNPsForSeqForm(snps=snpAll, seqHasSnps=thisSeqHasSnp) print(form) return render(request, 'myapp/SNPs-to-add-to-sequence.html', locals()) my urls.py urlpatterns = [ url(r'^SNPs-to-add-to-sequence_(?P<idSequence>.+)$', views.uploadSNPsToSeq, name='addSNPsSeq'), url(r'^upload_(?P<dataType>[A-Za-z-]+)_(?P<method>(single|batch))$', views.uploadData, name='upload'), ... url(r'^$', views.home, name='home') ] I have my 2 templates called upload_sequence-has-snp.html and SNPs-to-add-to-sequence.html. The 2 forms are OK because I have access to my first form and for example select a form.cleaned_data['seq_linked'] equal to TEST. I can see the result in the terminal of print(form) in uploadSNPsToSeq, but the last line of this view raise a NoReverseMatch error: NoReverseMatch at /myapp/SNPs-to-add-to-sequence_TEST Reverse for 'upload' with arguments '('', '')' not found. 1 pattern(s) tried: … -
Django angular error
I'm learning Angularjs and I want to integrate it with django. I'm following the tutorial in angularjs site. First I try the code in an static html page (not django), that works fine. html: <html ng-app="phonecatApp"> <head> <script src="angular.min.js"></script> <script src="app.js"></script> </head> <body> <!-- Use a custom component to render a list of phones --> <phone-list></phone-list> </body> </html> js: // Define the `phonecatApp` module var phonecatApp = angular.module('phonecatApp', []); // Register `phoneList` component, along with its associated controller and template angular. module('phonecatApp'). component('phoneList', { template: '<ul>' + '<li ng-repeat="phone in $ctrl.phones">' + '<span>{{ phone.name }}</span>' + '<p>{{ phone.snippet }}</p>' + '</li>' + '</ul>', controller: function PhoneListController() { this.phones = [ { name: 'Nexus S', snippet: 'Fast just got faster with Nexus S.' }, { name: 'Motorola XOOM™ with Wi-Fi', snippet: 'The Next, Next Generation tablet.' }, { name: 'MOTOROLA XOOM™', snippet: 'The Next, Next Generation tablet.' } ]; } }); When I try the same in django templates like this: {% extends 'qhcba/base.html' %} {% block ng_app %}phonecatApp{% endblock ng_app %} {% block content %} <div ng-controller="PhoneListController"> <div> {% verbatim %} <phone-list></phone-list> {% endverbatim %} </div> </div> {% endblock %} it renders the phone list code commented, like this: <phone-list><ul><!-- … -
problems getting bootstrap.js to work while using Django
I have a very simple site using the django templating engine. in this site i use Bootstrap for design and basic js. the css components from bootstrap totaly work but i cant get js to work: {% load staticfiles %} <!doctype html> <html lang="en"> <head> <title> blah </title> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'css/bootstrap.min.css' %}" type="text/css"/> </head> <body> <!-- Navbar --> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <a class="navbar-brand" href="/">blah</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarTogglerDemo02" aria-controls="navbarTogglerDemo02" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarTogglerDemo02"> <ul class="navbar-nav mr-auto mt-2 mt-lg-0"> <li class="nav-item active"> <a class="nav-link" href="/">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link" href="#">Link</a> </li> <li class="nav-item"> <a class="nav-link disabled" href="#">Disabled</a> </li> </ul> <form class="form-inline my-2 my-lg-0"> <input class="form-control mr-sm-2" type="search" placeholder="Search"> <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button> </form> </div> </nav> <!-- Space between Navbar and Body --> <div class="border-row" style="width:100%; margin-bottom: 15px;"></div> <!-- Fullscreen Container --> <div class="container-fluid" style="min-height:100%; width:100%;"> <p>hi</p> </div> <script src="{% static '/js/jquery.js' %}"></script> <script src="{% static '/js/bootstrap.min.js' %}"></script> </body> </html> screenshot of resulting page screenshot the css und js files are delivered to the browser as the following log will show, but i also … -
Django: Uploading a file to a REST API with a FileField in a model
So here is the context. I am using Django with Python3.6, and we're using Django REST Framework to build our REST API. I have a simple form on a page, but it is not submitted directly. I am calling manually our API using axios. Here's the code used when pressing the submit button: let form = new FormData(); form.append('name', this.game.name); form.append('video', this.game.video); form.append('icon', this.game.icon); axios.post("api/games/", form, {headers: { 'Content-Type': 'multipart/form-data', }}) Everything is fine here. My API receive the correct data, I can create my game object easily. The main issue is the 'video' field. It is registered as a FileField in my models.py name = models.CharField(max_length=255, unique=True) icon = models.ImageField(upload_to=user_directory_path) video = models.FileField(upload_to=user_directory_path) When submitting a MP4 video file (.mp4) that is like 500ko, it is working properly. But when I try to upload a file that is much greater, like 5 mo and with format QT (.mov), I got an error from django: ERROR 2017-11-23 16:59:31,831 exception Internal Server Error: /api/games/ Traceback (most recent call last): File "myawesomeproject/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "myawesomeproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "myawesomeproject/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "myawesomeproject/lib/python3.6/site-packages/django/views/decorators/csrf.py", … -
Permission denied error with PostgreSQL and Django. Giving rights to PostgreSQL user admin
I have Django app with PostgreSQL. The app has those environment variables: DATABASE_HOST=localhost DATABASE_USER=admin DATABASE_PASSWORD=admin Here is psql output: postgres=# CREATE USER admin WITH PASSWORD 'admin123'; ERROR: role "admin" already exists postgres=# select * from USER; current_user -------------- postgres (1 row) postgres=# GRANT ALL privileges ON DATABASE my_db to admin; GRANT When I try to take something from db I get ProgrammingError: permission denied for relation app_rangeslot. So, the questions: 1) If user admin have all rights, why I get permission denied error? 2) If user admin is created, why I cannot see it? -
Using uploaded image in frontend
I have a profile database for users in which I save their profile image. I am using DRF to create API's for this. Now when I save the profile data, it return JSON as: { "branch": "CSE", "year": 2014, "image": "static/profile_images/abhishek.jpg" } this data gets saved in database and even the image get uploaded to the desired folder. Now I want to access this image in the frontend(I am creating an android app in Ionic), so that the profile pic is viewed in the app's dashboard. How do I do it? At present simply going to the saved path is not working. -
How can I convert a selected name into a user ID in an HTML input form and populate the input field with it?
I'm creating a web application in Django. The premise: a user is attempting to create something new which is tied to a patient. Each patient in my database has an associated first name, last name, birth date, and MRN (an ID.) The user would be provided with a table/list of users to choose from. When the user clicks a name or a button next to a name, I want to populate the the "Patient" input field with the patient's MRN - not their name. How would I fill an HTML input field with the patient's MRN instead of their name? (Or, more broadly, how can I translate a selection to an input value and populate an input field with that value?) -
django - This field is required
I have two forms in my template and what I want to do is add the newly added model to an attribute of another model. The models are Customer and Order respectively. (Once I add a customer, i want to add an order with its customer, the newly added) Here is my customer views def add_customer(request): form = CustomerForm(request.POST or None) customers = Customer.objects.all() if form.is_valid(): customer = form.save(commit=False) customer.save() context = { 'form': OrderForm() } messages.success(request, "Customer added successfully!") return render(request, 'orders/add_order.html', context) context = {'form': form} return render(request, 'core/add_customer.html', context) Here is my order views def add_order(request): form = OrderForm(request.POST or None) orders = Order.objects.all() if form.is_valid(): order = form.save(commit=False) order.save() messages.success(request, "Order placed") return render(request, 'orders/index.html', {'orders': orders}) return render(request, 'orders/add_order.html', {'form': form}) Here is my template <a href="{% url 'core:add-customer' %}"> <p><em>Click this to add a new customer</em></p> </a> <form method="post"> {% csrf_token %} {% include 'core/form-template.html' %} <div align="center"> <button class="btn btn-success"> Submit </button> </div> </form> However, the order can't be added since it throws the error (This field is required) -
Iteration error in Django
I'm still a student so sorry if I make stupid mistakes and the code looks a lil ugly, I still need to clean it up. I'm busy with a project where we have to make an online webshop. The database is already set-up and so is the email-system, but whenever I try to implement the ordered data (items that got added to your ShoppingCart), I'm unable to specify the items in an email. A heads up, I have written a lot of info down below to make the error as clear as possible. This is the error I got: TypeError at /checkout/ 'OrderDetails' object is not iterable Error during template rendering 16 {% for createOrder in order %} This is the email html: <!--This order email--> {% load custom_tags %} {% load shoppingcart_tags %} {% block extrastyle %} <style type="text/css"> body.login {background-color: palegreen;} </style> {% endblock %} {% autoescape off %} <p>Beste klant,</p> <p></p> <p>U heeft zojuist een bestelling geplaatst op onze website voor de volgende producten:</p> {% block purchases %} {% for createOrder in order %} <h1>{{ orderDetails.orderNum }}</h1> <h1>{{ orderDetails.productNum }}</h1> <h1>{{ orderDetails.amount }}</h1> {% endfor %} {% endblock %} <p>Wij streven ernaar uw bestelling binnen 2 dagen … -
How to show shamsi date in django?
I'm trying to make django's default 'DateTimeField' to show Shamsi (Persian) calendar, but I have no idea of how to do it. Is there any way to make this type of field use Shamsi completely or use it as it is and just converting to Shamsi when showing on the template? -
How to distinguish between two forms in class based View
I have two form from which i got file input in single view. So my aim is to seprate files from one form from files from another. I would like to access somehow form attributes, preferably form fields attributes and based on this to make some processing in post view. Like: <form> <input type="file" id="test_file" name="file"> </form> class UploadedFileForm(forms.ModelForm): ... def post(self, request): form = UploadedFileForm(self.request.POST, self.request.FILES) and here i want to check if the file source form. In my case if, for instance, file is from the field with id test_file then do some processing, or else do another one. Currently i handle this situation having two different views one for each form, but want to combine it in one.