Django: UpdateView and ModelForm - python

I'm having a weird issue when using a ModelForm as a form_class for UpdateView.
First of all: When using the UpdateView without the form_class tag, everything works perfectly. However, when I try to use the ModelForm (because I want to add a MarkdownField) I get <mediwiki.views.MediwikiForm object at 0x7f990dfce080>displayed in my browser window. Just in plain text?
#template/mediwiki/create2.html:
<form action="" method="post">{% csrf_token %}
{{ form }}
<input type="submit" value="Save" />
</form>
#views.py:
class EntryUpdate(UpdateView):
model = Mediwiki
slug_field = 'non_proprietary_name'
template_name = "mediwiki/create2.html"
form_class = MediwikiForm⋅
#fields = '__all__' #this works...
#forms.py
class MediwikiForm(ModelForm):
# wiki_page_markdown = MarkdownxFormField()
class Meta:
model = Mediwiki⋅
fields = ['non_proprietary_name', 'category', 'wiki_page_markdown']
#models.py
class Mediwiki(models.Model):
non_proprietary_name = models.CharField(max_length = 100, unique = True)
category = models.ManyToManyField(Category)
wiki_page = models.TextField(blank = True)
wiki_page_markdown = models.TextField(blank = True)
def save(self):
import markdown
self.wiki_page = markdown.markdown(self.wiki_page_markdown)
super(Mediwiki, self).save() # Call the "real" save() method.
def get_absolute_url(self): # For redirect after UpdateView
return reverse('entry', kwargs={'slug': self.non_proprietary_name})
def __str__(self):
return self.non_proprietary_name
#urls.py
url(r'^mediwiki/(?P<slug>\D+)/edit$', EntryUpdate.as_view(), name="update"),
Any idea what might cause this error? Any help will be much appreciated...

Related

ModelFormset in Django CreateView

I'm still new to Django & I would like to know how can allow user to add more than 1 ReferrerMember on Registration form as I wanted to achieve similar to the image url below
https://imgur.com/a/2HJug5G
I applied modelformset but so far it's giving me an error where "membership_id" violates not-null constraint the moment I submitted the form.
I've searched almost everywhere to find how to implement this properly especially on class-based view instead of function based view but still no luck. If possible please help me point out on any mistakes I did or any useful resources I can refer to
models.py
class RegisterMember(models.Model):
name = models.CharField(max_length=128)
email = models.EmailField()
class ReferrerMember(models.Model):
contact_name = models.CharField(max_length=100)
company_name = models.CharField(max_length=100)
membership = models.ForeignKey(RegisterMember, on_delete=models.CASCADE)
forms.py
class RegisterMemberForm(ModelForm):
class Meta:
model = RegisterMember
fields = ['name', 'email', ]
class ReferrerForm(ModelForm):
class Meta:
model = ReferrerMember
fields = ['contact_name ', 'company_name ', ]
ReferrerMemberFormset = modelformset_factory(ReferrerMember, form=RegisterMemberForm, fields=['contact_name ', 'company_name ', ], max_num=2, validate_max=True, extra=2)
views.py
class RegisterMemberView(CreateView):
form_class = RegisterMemberForm
template_name = 'register.html'
def post(self, request, *args, **kwargs):
member_formset = ReferrerMemberFormset (request.POST, queryset=ReferrerMember.objects.none())
if member_formset .is_valid():
return self.form_valid(member_formset )
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['member_formset'] = ReferrerMember(queryset=ReferrerMember.objects.none())
return context
register.html
<form method="post">
{% csrf_token %}
{{form.as_p}}
{{member_formset.as_p}}
<input type="submit">
</form>

Search field in Django is not redirecting to detail view

I am adding a search field in my blog so people can put the name of the blog they want to read and a list of items come up and after clicking on any of the list items, it will redirect to the detail view. However, in my case,If I put anything in search, it is not redirecting to a detail view but going to http://127.0.0.1:8000/home/search/2 instead of http://127.0.0.1:8000/home/list/2/.
I have posted my models, views, URLs and template files below.
Is there any reverse method I need to use here to redirect and what changes I need in my template file?
models.py
from django.db import models
class Category(models.Model):
cat_name = models.CharField(max_length = 256, blank = True)
def __str__(self):
return self.cat_name
class Blog(models.Model):
name = models.CharField(max_length = 256, blank = True)
pub_date = models.DateTimeField('date published')
text = models.TextField(blank = True)
category = models.ForeignKey(Category, on_delete=models.CASCADE,
related_name='categories', verbose_name = 'blog_categories')
def __str__(self):
return self.name
views.py
from django.shortcuts import render
from homepage.models import Blog
from django.views.generic import TemplateView, ListView, DetailView
from homepage import models
from django.db.models import Q
class Home(TemplateView):
template_name = 'homepage/index.html'
class BlogListView(ListView):
context_object_name = 'blogs'
model = models.Blog
template_name = 'homepage/blog_list.html'
class BlogDetailView(DetailView):
context_object_name = 'blogs_detail'
model = models.Blog
template_name = 'homepage/blog_detail.html'
def get_queryset(self):
query = self.request.GET.get('q')
return Blog.objects.filter(
Q(name__icontains = query) | Q(name__icontains = query) )
class SearchResultsListView(ListView):
model = Blog
context_object_name = 'blog_list'
template_name = 'homepage/search_result_list.html'
def get_queryset(self):
query = self.request.GET.get('q')
return Blog.objects.filter(
Q(name__icontains = query) | Q(name__icontains = query) )
urls.py
from django.urls import path
from homepage import views
from homepage.views import SearchResultsListView
app_name = 'homepage'
urlpatterns = [
path('', views.Home.as_view(), name = 'index'),
path('list/', views.BlogListView.as_view(), name = 'blog-list'),
path('list/<int:pk>/', views.BlogDetailView.as_view(), name = 'blog-list'),
path('search/', SearchResultsListView.as_view(), name = 'search_result'),
]
index.html
<div class="grid-item-1">
<h1>G</h1>
<input type="button" name="" value="Back to Home" placeholder="">
<form action="{% url 'home:search_result' %}" method = 'get'>
<input type="text" name="q" placeholder="search">
</form>
</div>
search_result_list.html
{% for blog in blog_list %}
<ul>
<li>
{{blog.name}}
{{blog.address}}
here
</li>
</ul>
{% endfor %}
the URL redirects to http://127.0.0.1:8000/home/search/2 and its a 404 page.
how can I redirect it to the detail view page http://127.0.0.1:8000/home/list/1/ and see the detail of the list pulled by search result.
The reason this happens is because {{ blog.id }} just contains a number, for example 2. It will be appended to the URL. You can fix this by prepending the URL with a slash (/) and write list with:
{{blog.name}}
{{blog.address}}
here
But it is likely better to make use of the {% url … %} template tag [Django-doc]:
{{blog.name}}
{{blog.address}}
here
In your BlogDetailView, there is no q parameter, so you can remove the get_queryset:
class BlogDetailView(DetailView):
context_object_name = 'blogs_detail'
model = models.Blog
template_name = 'homepage/blog_detail.html'
# no get_queryset
Furthermore perhaps you should consider renaming the DetailView from blog-list, to blog-detail, or something similar.

Pre-populating a child models django create form with a parent's ID

I have followed the guidelines from This answer in order to pass Parent pk to the child creation page. At the moment though it is not working and I am seeing the following log.
[14/Jul/2017 13:15:37] "POST /catalog/productstatus/2/create/ HTTP/1.1" 200 4001
I'm not sure what I'm doing wrong, here is the code I currently have.
Models
Models.py
class Product(models.Model):
serial_number = models.CharField(unique=True, max_length=15)
class ProductStatus(models.Model):
serial_number = models.ForeignKey('Product', on_delete=models.CASCADE, null=True)
status = models.CharField(max_length=20, blank=True, default='Stock', help_text='Products status')
date = models.DateTimeField(auto_now_add=True)
View
class ProductStatusCreate(CreateView):
model = ProductStatus
template_name = 'catalog/productstatus_create.html'
form_class = ProductStatusModelForm
def form_valid(self, form):
productstatus = form.save(commit=False)
product_id = form.data['product_id']
product = get_object_or_404(Product, id=product_id)
productstatus.product = product
return super(ProductStatusCreate, self).form_valid(form)
def get_context_data(self, **kwargs):
context = super(ProductStatusCreate, self).get_context_data(**kwargs)
context['s_id'] = self.kwargs['product_id']
return context
def get_success_url(self):
if 'product_id' in self.kwargs:
product = self.kwargs['product_id']
else:
product = self.object.product.pk
return reverse_lazy('product_detail', kwargs={'pk': product})
Forms
class ProductStatusModelForm(forms.ModelForm):
class Meta:
model = ProductStatus
fields = ['status',]
def __init__(self, *args, **kwargs):
self.fields["product"] = forms.CharField(widget=forms.HiddenInput())
super(ProductStatusModelForm, self).__init__( *args, **kwargs)
templates/myapp/product_detail.html
New
urls.py
urlpatterns += [
url(r'^productstatus/(?P<product_id>\d+)/create/$', views.ProductStatusCreate.as_view(), name='productstatus_create'),
]
productstatus_create.html
{% extends "base_generic.html" %}
{% block content %}
<h2>New Product Status</h2>
</br>
<form action="" method="post">
{% csrf_token %}
<table>
<input type=hidden id="id_product" name="product" value="{{ s_id }}">
{{ form }}
</table>
<input type="submit" value="Submit" />
</form>
</br>
{% endblock %}
When looking at the page's source the value does get populated but when I submit the form nothing happens.
Why do you have views.ProductInstanceCreate.as_view() in your urls.py but the view you show is called ProductStatusCreate? Are you sure you are using the right view?
You are creating a 'product' hidden field in your form, but not providing a value for it anywhere. Your template output then has two product fields, and the latter (blank) is taken, so returns an error saying it is required.
None of this outputting the product ID to the template in order to read it back in is necessary - you always have the ID available to you in the URL kwargs.
You can get rid of your get_context_data, and the extra field code in the Form and template. Your form_valid can be something like:
def form_valid(self, form):
product = get_object_or_404(Product, id=self.kwargs['product_id'])
form.instance.product = product
return super().form_valid(form)
And product_id will always be in self.kwargs, so your get_success_url can be shorter too:
def get_success_url(self):
product = self.kwargs['product_id']
return reverse('product_detail', kwargs={'pk': product})

Pb initializing ModelForm

I am learning Django, and I have a problem with ModelForm. So I have an app which is named mini_url. In this app I have a model :
class MiniURL(models.Model):
url = models.URLField(unique=True)
code = models.CharField(unique=True, max_length=255)
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name='Date de création')
pseudo = models.CharField(max_length=30)
nb_acces = models.IntegerField(default=0)
I wanted to create a form based on my model, so I did this in a form.py file :
from django.forms import ModelForm
from mini_url.models import MiniURL
def MiniURLForm(ModelForm):
class Meta:
model = MiniURL
fields = ['url', 'pseudo']
And then in my view I have this :
from django.forms import ModelForm
from mini_url.models import MiniURL
def create_url(request):
if request.method == 'POST':
form = MiniURLForm(request.POST)
if form.is_valid():
new_url = MiniURL()
new_url.url = form.cleaned_data['url']
new_url.pseudo = form.cleaned_data['pseudo']
new_url.code = generer(5)
new_url.save()
else:
form = MiniURLForm()
return render(request, 'mini_url/create_url.html', {'form': form})
Finally my template (mini_url/create_url.html) which shows the form :
<p>
<form action="{% url "mini_url.views.create_url" %}" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit"/>
</form>
</p>
But when I try to acceed to the template I have this error :
MiniURLForm() missing 1 required positional argument: 'ModelForm'
And it shows me that the error is in my view at the line where there is :
form = MiniURLForm()
So I don't understand why it fails. I did what the doc says I think : https://docs.djangoproject.com/en/1.8/topics/forms/modelforms/#topics-forms-modelforms
Anyone can help me ?
You have accidentally defined MiniURLForm as a function instead of a form class.
Change
def MiniURLForm(ModelForm): # wrong
to
class MiniURLForm(ModelForm): # should be a class
When you defined MiniURLForm as a function, Django expected a positional argument as per your definition. Change it to a form class and it should work correctly.
Final Code:
class MiniURLForm(ModelForm):
class Meta:
model = MiniURL
fields = ['url', 'pseudo']

Trouble with Django ModelChoiceField

Hi bit of a beginner question about using django's modelchoicefield in a form I'm building.
I just need get django to display a drop down list of ingredients in a form. I've gotten to the point where the page renders but the form does not, I was getting errors before so I am kind of perplexed at the moment. I was hoping for some guidance.
Using python 2.7.6 and django 1.6.2. If I left anything out let me know.
Thanks!
Code is below:
views:
args = {}
#add csrf sercurity
args.update(csrf(request))
args['form'] = form
return render_to_response('newMeal.html', args)
form:
from django import forms
from models import meals, ingredients, recipe
class mealForm(forms.ModelForm):
breakfast = forms.ModelChoiceField(queryset=recipe.objects.all())
# Lunch = forms.ModelChoiceField(queryset=recipe.objects.all())
# Dinner = forms.ModelChoiceField(queryset=recipe.objects.all())
class Meta:
model = meals
fields = ('Breakfast','Lunch','Dinner','servingDate')
class recipeForm(forms.ModelForm):
class Meta:
model = recipe
fields = ('Name', 'Directions')
template:
{% extends "base.html" %}
{% block content %}
<p>New Meals go here!</p>
<form action="/meals/newmeal/" method="post">{% csrf_token %}
<table class="selection">
{{form.as_table}}
<tr><td colspan="2"><input type="submit" name="submit" value="Add Meal"></td></tr>
</table>
</form>
{% endblock %}
Model;
from django.db import models
import datetime
Create your models here.
class recipe(models.Model):
Name = models.CharField(max_length=200)
Directions = models.TextField()
pub_date = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return (self.id, self.Name)
class ingredients(models.Model):
Name = models.CharField(max_length=200)
Quantity = models.IntegerField(default=0)
Units = models.CharField(max_length=10)
Recipe = models.ForeignKey(recipe)
def __unicode__(self):
return self.Name
class meals(models.Model):
Breakfast = models.CharField(max_length=200)
Lunch = models.CharField(max_length=200)
Dinner = models.CharField(max_length=200)
servingDate = models.DateTimeField('date published')
did you import the mealForm:
some thing like :from app.forms import mealForm
form is a function. so try:
args['form'] = mealForm()
Note: don't use render_to_response. it is old use render instead(so don't even need csrf)::
from django.shortcuts import render
def...(request):
....
return render(request,'newMeal.html', {'form': mealForm()})

Categories