I would like to be able to use my external app data on django cms page.
I am able to use custom plugin data but not data from normal django app
I tried creating views to handle my data but how do I call this view from django cms pages?
here is exactly what I am asking for but his explanation is shallow and the link provided in the answer is no longer in use.
Here is my model:
class ExternalArticle(models.Model):
url = models.URLField()
source = models.CharField(
max_length=100,
help_text="Please supply the source of the article",
verbose_name="source of the article",
)
title = models.CharField(
max_length=250,
help_text="Please supply the title of the article",
verbose_name="title of the article",
)
class Meta:
ordering = ["-original_publication_date"]
def __str__(self):
return u"%s:%s" % (self.source[0:60], self.title[0:60])
My template has placeholders
{% load cms_tags %}
{% block title %}{% page_attribute "page_title" %}{% endblock title %}
{% block content %}
<section class="section">
<div class="container">
<div class="row">
<!-- header-->
<div class="col-lg-12">
<div class="updates">
{% placeholder "header" %}
</div>
</div>
<!-- header end-->
</div> <!-- end row -->
but I don't mind displaying this data anywhere on the template if not possible inside a place holder
I have a custom page that I am using in Django cms.
I would like to display the above data is a section in the Django cms page
If this model was inheriting from CMSPlugin then that would be easy because I could use a custom plugin in my placeholder
I expect to display the data from my model in the template.
I was able to achieve this by doing the following:
#plugin_pool.register_plugin
class ArticlesPluginPublisher(CMSPluginBase):
model = ArticlesPluginModel
name = _("Articles")
render_template = "article_plugin/articles.html"
cache = False
def render(self, context, instance, placeholder):
context = super(ArticlesPluginPublisher, self).render(
context, instance, placeholder
)
context.update(
{
"articles": Article.objects.order_by(
"-original_publication_date"
)
}
)
return context
The plugin model(ArticlesPluginModel) is just for storing the configurations for the instance of the plugin. Not the actual articles.
Then the render will just add to the context the relevant articles from the external app(Article)
You must somehow connect the ExternalArticle with a page object. For example
by defining the ExternalArticle as a page extension
or with an AppHook
or - low-tech - with a PageField on the ExternalArticle model
{% load cms_tags %}
<h1>{{ instance.poll.question }}</h1>
<form action="{% url polls.views.vote poll.id %}" method="post"> {% csrf_token %}
{% for choice in instance.poll.choice_set.all %}
<input type="radio" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" />
<label for="choice{{ forloop.counter }}">{{ choice.choice }}</label><br />
{% endfor %}
<input type="submit" value="Vote" />
</form>
Related
I don't understand how widgets work.
I tried this minimum example :
in my forms.py
class PartialResetForm(forms.Form):
date = forms.DateField(
label="Starting date",
widget=AdminDateWidget()
)
in my admin/intermediary_reset_page.html
{% extends "admin/base_site.html" %}
<!--Loading necessary css and js -->
{{ form.media }}
{% block content %}
<form action="" method="post">{% csrf_token %}
<!-- The code of the form with all input fields will be automatically generated by Django -->
{{ form }}
<!-- Link the action name in hidden params -->
<input type="hidden" name="action" value="custom_action" />
<!-- Submit! Apply! -->
<input type="submit" name="apply" value="Submit" />
</form>
{% endblock %}
in my admin.py as the definition of an action
def custom_action(self, request, queryset):
form = PartialResetForm()
return render(request, "admin/intermediary_reset_page.html", {
"items": queryset, "form": form
})
For now I don't care about the queryset, it will be my next topic. With this simple example, I wanted to have a calendar in order to help pick a date, but only a TextInput appeared. I believe it is due to the fact that AdminDateWidget inheritates from TextInput.
My question is why isn't it appearing as a calendar ? I imported the media and declared my widget, I don't understand what else I'm supposed to do.
you should declare type
AdminDateWidget(attrs={'type': 'date'})
And it should be enough ;)
Suppose im saving a url from a texbox given by user the URL is submitted by user and its saved to my models and now what i wanna do is let the user add different sections/clusters such as technology,sports etc from his end suppose where he inputs the URL there itself he can define that cluster/section and save that particular URL to the particular section/cluster he made or selected in the option is the section/cluster was already there! could anyone help or give me a small example for the same? what would be a better approach do it with django choices or some other way?
TIA.
ill paste the current code below :
form.py
class UrlSaveForm(ModelForm):
class Meta:
model = UrlSaveModel
fields = ['the_url']
models.py (below)
class UrlSaveModel(models.Model):
the_url = EmbedVideoField()
desc = models.CharField(max_length=200)
def __str__(self):
return self.desc
HTML for saving: save.html
{% extends 'base.html' %} {% block content %}
<form method="post" action="{% url 'func' %}">
{% csrf_token %}
<div class="form-group">
<label for="exampleFormControlTextarea1"
>Enter the URL here to save video to the library:</label
>
<textarea
class="form-control"
id="exampleFormControlTextarea1"
rows="2"
name="the_url"
placeholder="Enter the URL here"
></textarea>
<br />
<button type="submit" class="btn btn-primary mb-2">Save URL</button>
</div>
</form>
{% endblock %}
"""and little snippet of views.py"""
if form.is_valid():
print('form is valid')
posted_url = request.POST['the_url']
yt = YouTube(posted_url)
description = yt.title
print('description-extracted:', description)
print('Posted_url', posted_url)
obj = UrlSaveModel(desc=description, the_url=posted_url)
obj.save()
return HttpResponse('saved sucessfully!')
Is there any way how to update booleanField in the list view? In list view I have listed all my orders and I need to mark which are done and which are not done. I know I can update it via UpdateView, but that is not user friendly because I have to leave the listview page.
models.py
class Order(models.Model):
...
order = models.CharField(max_length = 255)
completed = models.BooleanField(blank=True, default=False)
views.py
class OrderIndex(generic.ListView):
template_name = "mypage.html"
context_object_name = "orders"
def get_queryset(self):
return Order.objects.all().order_by("-id")
mypage.html
{% extends "base.html" %}
{% block content %}
{% for order in orders%}
User: {{ order.user}} | Completed: {{order.completed}} <input
type="checkbox">
{% endfor %}
<input type="submit">
{% endblock %}
I am quite new to the django framework and have no idea how to make it work.
like this should look you javascript
const updateField = (order_id) =>{
var form = new FormData();
form.append('order_id', order_id);
fetch('{% url "url_updateField" %}', {
method:'post',
body:form,
mode:'cors',
cache:'default',
credentials:'include',
}).then((response)=>{
console.log('field update as well')
})
})
just add a function to your button on envent onclick
{% extends "base.html" %}
{% block content %}
{% for order in orders%}
User: {{ order.user}} | Completed: {{order.completed}} <input
type="checkbox" onclick="updateField({{order.pk}})">
{% endfor %}
<input type="submit">
{% endblock %}
then in your view you should have the below view to process the request
def updateField(request):
print(request.body.get('order_id'))
#you should update you model field here
return JsonResponse({'ok':True}, status=200)
This will help you How to work with ajax request with django
Combine the UpdateView with the part of the listView's functionality by adding to the UpdateView the extra context of the entire list of objects:
class OrderUpdateView(generic.UpdateView):
model = Order
form_class = OrderForm
....
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['orders'] = Order.objects.all().order_by("-id")
return context
Consider a simple template where the entire list is displayed on top, and the bottom has a form allowing the user to update a particular item in the list.
This approach purposefully avoids using Ajax and javascript.
documentation
There is a way to do this without any special magic, just post to an update view from your listview with the entire form filled out correctly in hidden form fields nothing special needs to be done anywhere else.
<!-- todo_list.html -->
<form method="POST" action="update/{{object.id}}/">
{% csrf_token %}
<input type="hidden" name="completed" value="true" />
<input type="hidden" name="name" value="{{object.name}}" />
<input type="hidden" name="due_date" value="{{object.due_date|date:'Y-m-d'}}" />
<input type="hidden" name="details" value="{{object.details}}" />
<button type="submit" class="btn btn-primary">Not Done</button>
</form>
This question already has an answer here:
Customize the styles of Django ClearableFileInput widget
(1 answer)
Closed 6 years ago.
I'm working on a web app that has photo upload functionality. I created a ModelForm to gather minimal user info plus a photo, and when I render it in HTML as {{ form.as_p }}, the field that allows the user to upload an image shows up just fine. The problem is, the form doesn't look good.
I need to be able to manually render the form in order to make it look better. I have written the HTML for this, and everything looks right except for the ImageFileField. Only the label gets rendered, not the upload button, checkbox to clear the file, etc.
What do I need to do to get the ImageFileField from the ModelForm to render correctly in my custom HTML? I've looked at the Django docs up and down, looked here on SO and can't find anyone else who's had this issue. Many thanks in advance!
forms.py snippet
class PostForm(forms.ModelForm):
class Meta:
model = Items
fields = ('title', 'description', 'image_file')
new_item.html snippet
<form enctype="multipart/form-data" method="post" action="" class="post-form">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.title.errors }}
<label for="{{ form.title.id_for_label }}">Title:</label><br>
{{ form.title }}
</div><br>
<div class="fieldWrapper">
{{ form.description.errors }}
<label for="{{ form.description.id_for_label }}">Description: </label><br>
{{ form.description }}
</div><br>
<div class="fieldWrapper">
{{ form.image_field.errors }}
<label for="{{ form.image_field.id_for_label }}">Image (optional):</label><br>
{{ form.image_field }}
</div>
<button type="submit" class="save btn btn-default">Save</button>
</form>
models.py snippet
class Items(models.Model):
title = models.CharField(max_length=1000, null=False)
description = models.TextField(max_length=1000, null=False)
image_file = models.ImageField(max_length=1000,
blank=True,
default='',
null=True,
upload_to='item_photos')
By default django ModelForm uses django.forms.ImageField and not ClearableInputField for django.db.ImageField as revealed at https://docs.djangoproject.com/en/1.9/topics/forms/modelforms/#field-types
And I do believe you actually meant ClearableFileInput
ClearableFileInput¶
class ClearableFileInput File upload input: ,
with an additional checkbox input to clear the field’s value, if the
field is not required and has initial data.
How you can make use of it is by changing the widget in the class meta
class PostForm(forms.ModelForm):
class Meta:
model = Items
fields = ('title', 'description', 'image_file')
widgets = {
'name': ClearableFileInput(),
}
I ended up using the Chrome tool to inspect the HTML source for the page that rendered correctly (but ugly), and used that as a guide to custom build the form in HTML to my liking. This is what I needed to add into my HTML form to get it right:
{% if item.image_file %}
Currently:
{{item.image_file.url}}
<input id="image_file-clear_id" name="image_file-clear" type="checkbox" /> <label for="image_file-clear_id">Clear</label><br />Change: <input id="id_image_file" name="image_file" type="file" /></p>
{% endif %}
{% if not item.image_file %}
<input id="id_image_file" name="image_file" type="file" /></p>
{% endif %}
SOLVED by Peter DeGlopper:
Thank you for your help it solved my issues, I really do appreciate it. I was banging my head against the table.
I didn't have to change my ModelForm. Looking at the HTML source I noticed in the input tag checked="checked" A subnet was being outputted as checked but it wasn't showing checked in my browser. This was in Firefox 24.2.0 in CentOS (On a VM), so I went to my Windows 7 host and loaded up Firefox 26.0 it worked, and worked fine in IE8 as well. That was weird, but it explains your confusion of that it should just work.
For saving the fields thanks to you I now see how I was over thinking it. And I am able to update the M2M field. I updated the TagUpdateView below to show the working code.
I have 2 issues with trying use an UpdateView with a M2M field...
The currently "tagged" subnets dont show up as checked in my template
How would I handle updating the M2M relationship in my TagUpdateView by overriding form_valid?
Any insight would be greatly appreciated.
Thanks.
Tag m2m models.py:
class Tag(models.Model):
tag = models.CharField(max_length=120)
group = models.ForeignKey(Group)
description = models.TextField(max_length=500)
subnet = models.ManyToManyField(Subnet, null=True, blank=True)
date_created = models.DateTimeField()
created_by = models.ForeignKey(User, related_name='tag_created_by')
date_modified = models.DateTimeField(auto_now=True)
modified_by = models.ForeignKey(User, related_name='tag_modified_by')
def __unicode__(self):
return self.tag
Tag ModelForm:
class TagForm(forms.ModelForm):
subnet = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple(), required=True, queryset=Subnet.objects.all())
class Meta:
model = Tag
exclude = ('date_created', 'created_by', 'date_modified', 'modified_by')
Tag views.py:
class TagUpdateView(UpdateView):
template_name = 'tag_update.html'
model = Tag
form_class = TagForm
def form_valid(self, form):
update_tag = form.save(commit=False)
update_tag.modified_by = self.request.user
update_tag.save()
form.save_m2m()
return super(TagUpdateView, self).form_valid(form)
My template "tag_update.html":
{% extends 'base.html' %}
{% load widget_tweaks %}
{% block title %}Tag {{ object.tag }} Update{% endblock %}
{% block content %}
<h1>Tag {{ object.tag }} Update</h1>
<br />
<form action="" method="post" role="form">{% csrf_token %}
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="id_tag">Tag Name</label>
{% render_field form.tag placeholder=form.tag.label class="form-control" %}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-2">
<div class="form-group">
<label for="id_group">Group</label>
{% render_field form.group placeholder=form.group.label class="form-control"%}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="id_description">Description</label>
{% render_field form.description placeholder=form.description.label class="form-control" rows="5" %}
</div>
</div>
</div>
<div class="row">
<div class="col-sm-6">
<div class="form-group">
<label for="id_checkbox">Link to Subnets</label>
{{ form.subnet }}
</div>
</div>
</div>
<br />
<button type="submit" class="btn btn-primary">Submit</button>
</form>
<br />
{% endblock %}
You're overthinking it. Handling this kind of relationship can be a little bit complicated if you need to track information on the relationship model itself (like a modified timestamp for when a particular subnet/tag pair was created) but for the model relationships you've shown here, form.save_m2m() is sufficient - it handles the m2m relationship for you.
You wouldn't even need that if you didn't need to use commit=False on your initial form save so you can set your modified_by field.
For prepopulation - mostly this looks to me like it should follow the normal behavior and prepopulate. I would probably just use the widget class rather than explicitly instantiating it (widget=forms.CheckboxSelectMultiple rather than widget=forms.CheckboxSelectMultiple()) but I don't see why that would affect it.
For both problems, you might have good results by starting with a simple ModelForm with no customizations on subnet, just exclude set. Once that's working, put in the special view code to handle modified_by. Once that's working, change to a custom widget declaration for subnet - maybe initially using the meta widgets override dictionary rather than a custom field declaration for the first pass.