django_markdown doesn't work on my template - python

I'm using the module django markdown and it doesn't work on my template, but it does on django admin
My Django version is 1.8.5 and I'm using the latest version of django markdown
I followed the steps showed in the repository's README https://github.com/klen/django_markdown
setup ( add django_markdown in settings and url are both ok )
in model.py ( migrate is ok )
from django_markdown.models import MarkdownField
class MyModel(models.Model):
description = MarkdownField()
python manage.py collectstatic is ok
forms.py
class BidForm(BaseBidForm, forms.ModelForm):
class Meta:
model = Bid
fields = ('name', 'description')
description = forms.CharField(widget=MarkdownWidget())
admin.py
#admin.register(models.Bid)
class BidAdmin(admin.ModelAdmin):
formfield_overrides = {MarkdownField: {'widget': AdminMarkdownWidget}}
template .html
{% load django_markdown %}
{% for field in form %}
{% if field.html_name == 'description' %}
<div class="col-md-7">
<div class="form-group">
<label for="{{ form.description.html_name }}">{% trans "Descripción" %} <span class="red">*</span> <small class="required">(obligatorio)</small></label><br>
<textarea id="new" class="form-control {{ field.errors|yesno:'error,' }}" rows="3"
name='{{ form.description.html_name }}'
placeholder="{% trans "ejemplos" %}"
value="{% if form.description.value %}{{ form.description.value }}{% endif %}"></textarea>
{% markdown_editor "#new" %}
{% markdown_media %}
</div>
</div>
{% endif %}
{% endfor %}

Related

django: delete pevious photo while adding a new photo

I am developing a user profile where users can add profile picture. Adding the picture is working fine but when I want to add a new photo, old photo doesn't go away. My django version is 3.1 and I have tried django-smartfields but still it is not working. Can anyone help?
views.py
from smartfields import fields
class Profile_Pic(models.Model):
user = models.ForeignKey(User, default='', null=False, on_delete=models.CASCADE, related_name='userPic')
profile_pic = fields.ImageField(upload_to='media', default='admin_car/static/images/img_avatar.png', blank=True)
class Meta:
db_table = 'Profile_Pic'
user_image.html
{% extends 'datas/base.html' %}
{% block content %}
{% load static %}
<h1 class="text-center" style="color: white">Add Profile Picture</h1>
<br><br>
<div class= "col-md-6.offset-md-3">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% if form.errors %}
<div class="alert alert-warning alert-dismissable" role="alert">
<button class="close" data-dismiss="alert">
<small><sup>x</sup></small>
</button>
<p>Data Error, Please Check Again.....</p>
{% for field in form %}
{% if field.errors %}
{{ field.errors }}
{% endif %}
{% endfor %}
</div>
{% endif %}
{{ form.as_p }}
<input type="submit" value="Save" class="btn btn-primary">
</form>
</div>
{% endblock %}
If your image is being updated in your static/image folder but not in the browser, this is because the browsers cache your static files and they don’t change readily. But there is work around you can use ‘whitenoise’
Follow these steps.
Clear your browser cache to erase already existing cache.
pip3 install whitenoise
Then add the following to the end of your settings.py
if DEBUG:
MIDDLEWARE = [
'whitenoise.middleware.WhiteNoiseMiddleware',
] + MIDDLEWARE
INSTALLED_APPS = [
'whitenoise.runserver_nostatic',
] + INSTALLED_APPS
Then rerun your server the static files won’t be cached anymore

How To Provide A Class To Fields In A Django Template?

I was working a project on mine, in which I needed to provide a class to a field in form which is a input box, but don't know how to do so.
My Template:
{% extends 'diary/base.html' %}
{% block title %}Register{% endblock title %}
{% block content %}
{% load staticfiles %}
<link rel= "stylesheet" type= "text/css" href = "{% static 'users/register.css' %}">
<div id="login-box">
<div class="left-box">
<h1>Register</h1>
<form action="{% url 'register' %}" method="post">
{% csrf_token %}
{% for non_field_error in form.non_field_errors %}
<p>{{ non_field_error }}</p>
{% endfor %}
{% for field in form %}
{{ field }}
{% for error in field.errors %}
<p>{{ error }}</p>
{% endfor %}
{% endfor %}
<input type="submit" value="SIGN UP" name="signup-button" class="signup-btn">
</form>
</div>
<div class="right-box">
</div>
</div>
{% endblock content %}
In this specific part:
{% for field in form %}
{{ field }}
{% for error in field.errors %}
I want to provide a class to {{ field }}.
I tried this:
{{ field(class="txtb") }}
This is how I use to provide a class in Flask, but in Django this didn't worked.
Any Help Would Be Appreciated!
django-widget-tweaks
I'm using django-widget-tweaks module for set HTML attribute in templates.
installation
install module using pip install django-widget-tweaks
add to INSTALLED_APPS in settings.py
INSTALLED_APPS = [
...
'widget_tweaks',
...
]
{% load widget_tweaks %} in templates file
usage
in templates code:
{% load widget_tweaks %}
...
{% for field in form %}
{% render_field field class="txtb" %}
...
in HTML, looks like this:
<input class="txtb" ... ...>
reference django-widget-tweaks github page for more information.
manually
Detailed description is in here
forms.py:
class YourForm(forms.ModelForm):
modelfield = forms.CharField(
...,
widget=forms.TextInput(
attrs={
'class': 'txtb'
}
}
)
class Meta:
model = ...
fields = ...
And I have a lot of information about django to simpleisbetterthancomplex.com
django-widget-tweaks also learned here

MultiValueDictKeyError with modified inline template in Django admin

In Django 1.11, I have 2 models, Foo and Bar:
class Foo(models.Model):
name = models.CharField()
class Bar(models.Model):
name = models.CharField()
foo = models.ForeignKey(Foo)
My admin.py looks like this:
class BarInline(admin.StackedInline):
model = Bar
template = 'admin/edit_inline/list.html'
class FooAdmin(admin.ModelAdmin):
fields = ('name')
inlines = [BarInline]
I use a customised template to show the Bar inline form, because I don't want the forms, just links to the edit pages for each Bar. list.html looks like this:
{% load i18n admin_urls static %}
<div class="js-inline-admin-formset inline-group" data-inline-type="stacked">
<fieldset class="module {{ inline_admin_formset.classes }}">
<h2>{{ inline_admin_formset.opts.verbose_name_plural|capfirst }}</h2>
{{ inline_admin_formset.formset.management_form }}
{% for inline_admin_form in inline_admin_formset %}<div class="inline-related{% if inline_admin_form.original or inline_admin_form.show_url %} has_original{% endif %}{% if forloop.last %} empty-form last-related{% endif %}">
<h3 style="overflow:auto"><span style="float:left">{{ inline_admin_formset.opts.verbose_name|capfirst }}: {% if inline_admin_form.original %}{{ inline_admin_form.original }}{% else %}#{{ forloop.counter }}{% endif %}</span><span style="float:right">{% if inline_admin_form.original %}Change Delete{% endif %}</span>
</h3>
</div>{% endfor %}
<div class="add-row">
Add a Bar
</div>
</fieldset>
</div>
The problem is that when I edit an existing Foo, and click Save, I get the error:
MultiValueDictKeyError at /admin/app/foo/1/change/
"'bar_set-0-id'"
EDIT: Stacktrace
If you don't want the form for the inline, the easiest approach is to not make the field(s) editable. This will render the objects with their values, but not editable in a form. The other way to display this is admin.TabularInline.
The options for inlines can be found here; https://docs.djangoproject.com/en/2.1/ref/contrib/admin/#inlinemodeladmin-options
The option that you will likely want to enable is show_change_link
What you'd end up with is something like;
class BarInline(admin.StackedInline):
model = Bar
fields = ('name', )
readonly_fields = ('name', )
show_change_link = True
For anyone interested, I ended up extending the template. I created a file change_form.html in templates/admin/app/foo/, and overrode the after_related_objects block:
{% extends 'admin/change_form.html' %}
{% load admin_urls %}
{% block after_related_objects %}
<div class="js-inline-admin-formset inline-group">
<fieldset class="module">
{% for bar in original.bar_set.all %}
<h3>
{{ bar.name }}
Change
</h3>
{% endfor %}
</fieldset>
</div>
{% endblock %}

Django user selects multiple images from gallery and saves it as strings in database backend

Im trying to create a form where the user selects from a gallery of images and it saves it to the database. The code below currently renders some radio buttons in the html output. Is there anyway I can change these to images i have saved in a static directory so the user can click on images instead? Would be great if I could change what it saves in the database to what I needed instead of image urls as well. Theres lots of documentation on uploading images but not much I could find on selecting images. Im using django 1.9.7 and python 3.5
models.py
client_choices = (('client1', 'Client 1'),
('client2', 'Client 2'),
('client3', 'Client 3'),
('client4', 'Client 4'),
('client5', 'Client 5'))
class ClientSelect(models.Model):
client = MultiSelectField(choices=client_choices)
forms.py
from app.models import ClientSelect
class ClientSelectForm(forms.ModelForm):
class Meta:
model = ClientSelect
fields = '__all__'
views.py
class FormWizard(SessionWizardView):
template_name = "app/clientchoices.html"
#define what the wizard does when its finished collecting information
def done(self, form_list, **kwargs):
form_data = process_form_data(form_list)
return render_to_response('app/about.html', {'form_data': form_data})
urls.py
url(r'^clientchoices$', FormWizard.as_view([ClientSelectForm]) , name='clientchoices'),
clientchoices.html
{% load staticfiles %}
{% block content %}
<section class="content">
<div class="container">
<div class="fit-form-wrapper">
<h2>Client Choices</h2>
<p>Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
{% for field in form %}
{{field.error}}
{% endfor %}
<form action="{% url 'clientchoices' %}" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button class="btn btn-brand" name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">"First Step"</button>
<button class="btn btn-brand" name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">"Previous Step"</button>
{% endif %}
<input class="btn btn-brand" type="submit" value="Submit" />
</form>
</div>
</div>
</section>
{% endblock %}
Any help is appreciated thank you

Adding bootstrap or sylilng to django built in forms

I just started my first app with django. I have built forms previously with bootstrap and custom styling. Now i came to know about django built-in forms with models. i have written the code for this but found that there is not styling and it's look so ugly. i want to add my custom styling to this form how can i do this. here is my code.
model.py
class Message(models.Model):
MessageID = models.AutoField(verbose_name='Message ID',primary_key=True)
MessageSubject = models.CharField(verbose_name='Subject',max_length=255,null=True,blank=True)
MessageContent = models.TextField(verbose_name='Content',null=True,blank=True)
MessageType = models.CharField(verbose_name='Message Type',max_length=255,default='Email',null=True,blank=True)
forms.py
from django import forms
from django.forms import ModelForm
from Apps.SendMessage.models import Message
class Message_form(ModelForm):
class Meta:
model = Message
views.py
def add_message(request):
message_form = {'message_form': Message_form}
print request.POST.get('Subject')
return render_to_response('sendmessage_form.html', message_form, context_instance=RequestContext(request))
and sendmessage_form.html
{% extends "base.html" %}
{% block Content %}
<div class="container">
<!-- Contacts -->
<div id="contacts">
<div class="row">
<!-- Alignment -->
<div class="col-sm-offset-3 col-sm-4">
<!-- Form itself -->
<form name="sentMessage" action="" method="POST" class="well" id="contactForm" novalidate>
{% csrf_token %}
{{ message_form }}
<button type="submit" class="btn btn-primary btn-sm pull-right">Send</button><br />
</form>
</div>
</div>
</div>
</div>
{% endblock %}
You're looking for Widgets!
From the documentation:
from django import forms
class CommentForm(forms.Form):
name = forms.CharField()
url = forms.URLField()
comment = forms.CharField(widget=forms.Textarea)
In your example:
You're using Bootstrap and therefore a simple css class (form-control) in each field will make it look great:
class Message_form(ModelForm):
class Meta:
model = Message
fields = ['MessageSubject', 'MessageContent', 'MessageType']
widgets = {'MessageSubject': forms.TextInput(attrs={'class': 'form-control'}),
'MessageContent': forms.Textarea(attrs={'class': 'form-control'}),
'MessageType': forms.TextInput(attrs={'class': 'form-control'}),}
Another thing, you don't need to explicit define MessageID. All Django models have a primary key like the one you defined (check the docs).
Use Django Bootstrap3 app. It provides form fields and template tags for displaying horizontal and vertical bootstrap forms:
{% load bootstrap3 %}
<form action="." method="post" class="form">
{% csrf_token %}
{% bootstrap_form form %}
<button type="submit" class="btn btn-primary">Submit</button>
</form>
I've been using crispy_forms and it's working very well with bootstrap.
pip install django-crispy-forms
In your template:
{% load crispy_forms_tags %}
<form method="POST">
{% csrf_token %}
{{ form|crispy }}
</form>
In template:
{{ form|as_p}}
in forms.py:
select = forms.CharField(widget=forms.Select(choices=select_choices, attrs={'class ':'form-control'}))
name = forms.CharField(widget=forms.TextInput(attrs={'class ':'form-control'}))

Categories

Resources