Well I know that what I'm doing is not very feasible, but I wanted to know if there's any way to do this.I want to create a portfolio blog to post some 3d renders, for that I want to have more control over the structure of the page. for this I created two models (one for the post and another to receive the images, linking them to the post through a foreign key) so that I could have an indefinite number of images, the problem came when I decided that I wanted to be able to choose the one positioning of the images according to my need/desire, for that I did the following:
I used django summernote temporarily to be able to test the written posts, I knew that it would probably not be possible to do this because the content sent from the models is static.
I have the following models:
class Post(models.Model):
titulo_post=models.CharField(max_length=255, verbose_name='Titulo')
autor_post=models.ForeignKey(User, on_delete=models.DO_NOTHING, verbose_name='autor')
data_post=models.DateTimeField(default=timezone.now, verbose_name='Data publicação')
conteudo_post =models.TextField()
publicado_post=models.BooleanField(default=False, verbose_name='Status publicação')
def __str__(self) :
return self.titulo_post
and:
class Estudo(models.Model):
imagem=models.ImageField(upload_to='estd_img/%Y/%m/%d', blank=True, null=True)
post=models.ForeignKey(Post, on_delete=models.CASCADE)
I tried to put the following value in the field "conteudo_post" through the administrative area to see if it would work
<div class="container">
<div class="col-10 mx-auto">
<img class="img-fluid " src="{{imagem.0.url}}" alt="">
</div>
</div>
as I thought it didn't work, when I use {{post_conteudo}} the rendered html displays an escaped version of the content, when I use {{post_conteudo |safe}} it creates the image container, but is not able to find it. when checking the browser's developer mode I can see that the value of {{image.0.url}} was not processed and it remains in that format in the final html
Related
In my frontpage.html. I have two buttons that link to the different categories of products I have I was using a for loop to get the slug needed for the URL link In the button, but this causes issues because it renders two buttons for each category i created in the models. My question: Is there a way for Django to only use one of these category slugs so I can specifically pick which URL it will render? I attached a picture of the frontpage.html file notice the for loop I am using to get the category slug that is being used to render the correct detail page. a for loop won't work since i have multiple categories
HTML
{% for category in menu_categories %}
Get Started
{% endfor %}
models.py for categories
class Category(models.Model):
title = models.CharField(max_length=255)
slug = models.SlugField(max_length=255)
ordering = models.IntegerField(default=0)
Here is the models.py as well. I was thinking there should be a way to explicitly call a specific slug and not render both buttons right next to each other
I'm new to django and I really have no idea how should I structure a website for the purpose of posting articles (like tutorials).
I'm not asking for specific code, but how does it work?
Should I make a base template and a html file for every single article that I'll post? If so, how should be the folder structure in the project? How can I show a list of all those articles and redirect to them if a user clicks on it? Should I link them to a database entry? How can I do that?
I'm asking those things because I only did things that involved reading content from the database/model and showing it on a template, but articles need images and other special construction that a blog textfield would not be enough.
If it is too confusing, just say so, and I'll try to put in another words, I'm really struggling to put my question into words.
I think you are just starting with Django, and if that is correct, I suggest you to start by making a hello world app to have a quick grasp of how django works, here is a good tutorial.
If you aren't just skip that part and start by writing down the requirements.
If you want your blog articles to have a header image, or a special text field in which you can write rich text, or even if you want to build a categories/tag system, write that in your requirements.
For each thing you would like to have django has already some ways to solve it.
For example for the image of the article you will use a django model field name ImageField.
I'll give you a really basic reference for the article model (You'll have to start a project and create an app).
# models.py
from django.db import models
class Article(models.Model):
title = models.CharField(max_length=140)
body = models.TextField()
image = models.ImageField(upload_to="blog/images")
created_on = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
Remember to make use of views and template language, but if you need some help with the image in the template just use this:
{% if post.image %}
<img src="{{ post.image.url }}" title="Post image">
{% endif %}
Also you have to realize that you'll need a hosting service like heroku or amazon for your app, and a media CDN to host the images of your posts. If you decide to use heroku i recommend to use Cloudinary and here is a tutorial.
If you need some inspiration feel free to checkout my blog.
I am trying to create a Django app where a user (say a researcher or a teacher) can create content for other users (participants or students) where any given page may include any number of content items (such as surveys questions, text, and/or images), and these items can be arranged by the teacher in any order on a page.
I'm taking an approach similar to the last chapters (10-12) of the book Django by Example. The app from those chapters comes very close to giving an example of my case using an e-Learning platform app, but they only allow teachers to create Content like Text and Images, they do not allow teachers to create survey questions for students. Here is the general approach that I am following.
The book models content for text and images for a given page like so:
class Content(models.Model):
page = models.ForeignKey(Page, related_name='contents')
content_type = models.ForeignKey(ContentType,
limit_choices_to={'model__in':('text',
'image')})
object_id = models.PositiveIntegerField()
item = GenericForeignKey('content_type', 'object_id')
order = OrderField(blank=True, for_fields=['page'])
class Meta:
ordering = ['order']
class ItemBase(models.Model):
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
abstract = True
def render(self):
return render_to_string('courses/content/{}.html'.format(
self._meta.model_name), {'item': self})
class Text(ItemBase):
content = models.TextField()
class Image(ItemBase):
file = models.FileField(upload_to='images')
There's an interface for teachers to fill out and order this content for a page.
Content is rendered within a template like so:
<div class="page">
{% for content in page.contents.all %}
{% with item=content.item %}
<h2>{{ item.title }}</h2>
{{ item.render }}
{% endwith %}
{% endfor %}
</div>
And the html used in the render method for a Text Content is simply:
{{item.content|linebreaks|safe }}
I don't find it difficult to extend this with QuestionTypes that extend ItemBase (similar to Text and Image models), as well as creating a StudentAnswer model for storing answers in the database.
I would probably override ItemBase render and put it into the QuestionType model so that I could pass a StudentAnswer model form into the context for the QuestionType html file.
I could then just have the html that is rendered contain {{ form }} for simplicity sake, and we now have a question that acts like any other content item and can be ordered with all of the others. This assumes that the HTML that contains the content has a form tag that encompass all of the rendered content items.
My problem is handling the POST request in the view. I have no idea how to validate and save answers from multiple forms on any given single page generated in this way. Examples I find assume a consistent number of forms that you know by name and are of different types.
I've also played around with the idea of creating a single dynamically generated form, but the examples I've seen for that assume you will loop through the fields in the template and display them in order rather than my requirement that a teacher determines the order which may include text or images in-between questions.
Is there a way to create what I'm looking for or can someone point me in the right direction?
I have a app where users can register their company and then select a number of settings from a list. Both the company and services are different models.
class Company(models.Model):
name = models.CharField(max_length=100)
(...)
class Service(models.Model):
name = models.CharField(max_length=100)
linked_companies = ManyToManyField(Company, blank=True)
What I want is to have a large list of services, with checkboxes behind their names, so the owner can quickly select the services that he wants to connect to his model. This used to be done through the admin interface, but due popular demand this feature is moved to 'the front'.
The problem is that I do not know how to fit this into the traditional (generic) view/form combinations that we' ve been using so far, since two different models are involved.
I am trying a more custom solution, but have hit a wall and I am wondering if you could help me. I have created a html page that should display both the list of services and a 'save' button.
<form action="." method="POST" class="post-form">{% csrf_token %}
<ul>
{% recursetree services %}
<li>
<label><input type="checkbox" name='service' value={{ node.pk }}><h3>{{ node.name }}</h3></label>
{% if not node.is_leaf_node %}
<ul class="children">
{{ children }}
</ul>
{% endif %}
</li>
{% endrecursetree %}
</ul>
<button type="submit" class="save btn btn-default">Add Selected
</button>
</form>
I am using the following ModelForm:
class FacetForm(forms.ModelForm):
class Meta:
model = Services
fields = ['linked_tenants', 'name']
widgets = {
'linked_tenants' : CheckboxSelectMultiple()
}
This HTML page seems to work as intended, showing a long list of services with checkboxes after their names.
However, I have trouble creating a function view. Together with a collegue the following view was created
class FacetList(TenantRootedMixin, TemplateView):
def get_context_data(self, **kwargs):
d = super(ServiceList, self).get_context_data(**kwargs)
d['services'] = Services.objects.all()
d['current_company'] = self.context.company.id
return d
def form_valid(self, *args, **kwargs):
return super(ServiceList, self).form_valid(*args, **kwargs)
This view works in the sense that it shows all of the relevant information (with the checkboxes). If I change the query to filter the services by 'company id'. the view works as desired as well.
The problems I have revolve around the fact that pressing 'save'. crashes the program, throwing the following error.
'super' object has no attribute 'post'
Our program works mostly through generic classbased views and modelforms, so we have relativly limited experience with creating our own custom solutions. By my own estimation the problem seems to be twofold:
The view is probably not configured right to process the 'post' data
It is questionable if the data will be processed to the database afterwards.
Though are 'sollution' is currently flawed, are we looking in the right direction? Are we on the right way to solve our problem?
Regards
I believe you are on the right track. What I would suggest is to not be afraid to move away from generic views and move toward a more custom solution (even if you are inexperienced with it.)
The first routine that comes to my mind would be as follows:
gather all the id's that were checked by the user into a list from request.POST
Update the appropriate object's M2M field to contain these new id's.
Save the fore-mentioned object.
[Edit]
One thing I have trouble with is gathering the ID' s from the request.POST. Could you provide me with an example on how to do this?
Sure, from your HTML file I see you are creating inputs with name=service. That leads me to believe you could do something like:
ids = request.POST.get('service')
but to teach you how to fish rather than giving you a fish, you should try to simply:
print request.POST.items()
This will return and print to the console everything that was posted from your form to your view function. Use this to find out if you are getting a list of id's from the template to the server. If not, you may have to re-evaluate how you are building your form in your template.
Your first point is correct: TemplateView has no "post" method defined and that is why you get the error message when you call super().form_valid. You must either define it yourself or use a CBV which has a post method that you can override (e.g. UpdateView)
And I also believe that your second point is correct.
You would need to use an UpdateView to use the built in functionality (or CreateView).
I had a similar problem to solve (selecting values from many-to-many fields in the front-end) and I ended up with doing it "by hand" because I could not get it to work with CBV. "by-hand" => parse the values from the form, update the database, return HttpResponse
You might want to look at ModelFormSets:
https://docs.djangoproject.com/en/1.11/topics/forms/modelforms/#model-formsets
Hope this helps!
Alex
I have a form which allows you to upload an image, but I want to know if it is possible to customise the markup that Django generates.
In the model it is created as an ImageField:
logo = models.ImageField(blank=True, null=True)
In the template I am creating an 'upload' form field using
{{ form.logo }}
This is the markup that gets generated:
Currently: dog.jpg
<input id="logo-clear_id" name="logo-clear" type="checkbox">
<label for="logo-clear_id">Clear</label>
<br>Change: <input id="id_logo" name="logo" type="file">
I want to know if I can change that markup by drilling down further, so that I can for example nest the checkbox to clear the image within its label. I also would like to use my own markup to separate the option to clear the form field from the option to upload a new one. However, I can't find any documentation on how to do this. I've tried outputting
{{ logo.logo-clear }}
directly but this throws an error.
The solution was to create a custom version of the widget being used in my forms.py: https://docs.djangoproject.com/en/1.10/_modules/django/forms/widgets/#ClearableFileInput
from django.forms.widgets import ClearableFileInput
class CustomImageFieldWidget(ClearableFileInput):
template_with_clear = '<label for="%(clear_checkbox_id)s">%(clear)s %(clear_checkbox_label)s</label>'
class OrganisationProfileForm(OrganisationCreateForm):
class Meta(OrganisationCreateForm.Meta):
widgets = {
'logo': CustomImageFieldWidget,
}