I have removed some useless branch from my git and now one function on my website does not work. It is about add_recipe does not work. When I am trying to add it and every field is filled, i push the button "add recipe" it shows that ingrediend field is required.
View:
def add_recipe(request):
add_recipe = RecipeForm(request.POST)
print(add_recipe['ingredients'].value())
if add_recipe.is_valid():
add_recipe.save()
return redirect('success_added_recipe')
return render(request, 'drinks/add_recipe.html', {'RecipeForm': add_recipe})
Form:
class RecipeForm(ModelForm):
class Meta:
model = Recipe
fields = ['recipe_name', 'preparation', 'ingredients', 'recipe_image']
debug.log
(0.000) SELECT "django_migrations"."app", "django_migrations"."name" FROM "django_migrations"; args=()
(0.001) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient" WHERE "drinks_ingredient"."id" IN (12); args=(12,)
(0.000) SELECT "drinks_ingredient"."id", "drinks_ingredient"."ingredient_name" FROM "drinks_ingredient"; args=()
"POST /accounts/add_recipe/ HTTP/1.1" 200 1637
(0.002)
model:
class Recipe(models.Model):
recipe_name = models.CharField(max_length=250)
preparation = models.CharField(max_length=1000)
ingredients = models.ManyToManyField(Ingredient)
recipe_image = models.ImageField(upload_to='images/', default='')
def __str__(self):
return self.recipe_name
template:
<h1>Add recipe</h1>
<form method="post" action="{% url 'add_recipe' %}">
{% csrf_token %}
<table>
{{RecipeForm}}
</table>
<input type="submit" value="Add recipe"/>
</form>
Just add blank=True in your ManyToManyField
class Recipe(models.Model):
recipe_name = models.CharField(max_length=250)
preparation = models.CharField(max_length=1000)
ingredients = models.ManyToManyField(Ingredient,blank=True)
recipe_image = models.ImageField(upload_to='images/', default='')
def __str__(self):
return self.recipe_name
Related
I have a "project" model that has a "status" field. The status can be active, paused, or complete. I want to be able to update the field via form on the project detail view.
I have read a few solutions to this problem but, as a newbie, I haven't been able to get this to work. When I submit the form I get an http 405 error and the instance is not updated.
the model:
class Project(models.Model):
title = models.CharField(max_length= 200)
description = tinymce_models.HTMLField()
status = models.CharField(max_length=20, choices=PROJECT_CHOICES, default="active")
date = models.DateTimeField(auto_now_add=True, null=True)
created_by = models.ForeignKey(CustomUser, editable=False, null=True, blank=True, on_delete=models.RESTRICT)
objects = ProjectManager()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('company_project:project_detail', args=[str(self.id)])
the view
class CompanyProjectsDetailView(DetailBreadcrumbMixin, FormMixin, DetailView):
model = Project
id = Project.objects.only('id')
template_name = 'company_accounts/project_detail.html'
context_object_name = 'project'
form_class = ProjectStatusForm
notescount = Project.objects.annotate(num_notes=Count('notes'))
documentscount = Project.objects.annotate(num_documents=Count('project_documents'))
todoscount = Project.objects.annotate(num_documents=Count('todo_group'))
def form_valid(self, form):
project = get_object_or_404(Project, id=self.kwargs.get('pk'))
theform = form.save(commit=False)
theform.project = project
form.save()
return super(CompanyProjectsDetailView, self).form_valid(form)
the form
class ProjectStatusForm(forms.ModelForm):
class Meta:
model = Project
fields = ['status']
labels = {'status': 'project status'}
widgets = {
'status': forms.Select(attrs={'id':'PROJECT_CHOICES'}),
}
On the page I use this code to add the form
<form action="" method="post">
{% csrf_token %}
{{ form.media }}
{{ form|crispy }}
</br>
<input type="submit" value="save">
</form>
I am a beginner and learning django, here i want to let the user to select items multiple times in a m2m field, for example here i have a icecream model with flavor class linked to it in a m2m rel, when the form is displayed in the template i want user to select 1 option many times.
my models:
class IceCream(models.Model):
hold_choice = (
('Cone', 'Cone'),
('Cup','Cup'),
)
type_name = models.ForeignKey('IceCreamType', on_delete=models.CASCADE, null=True, blank=True)
flavor = models.ManyToManyField(Flavor, verbose_name='total scopes')
toppings = models.ManyToManyField(Topping)
holder = models.CharField(max_length=4, choices=hold_choice, default='Cone')
number_of_icecreams = models.PositiveIntegerField(default=1)
def __str__(self):
return str(self.type_name)
#property
def total_scope(self):
return self.flavor_set.all().count()
the flavor model has some options:
class Flavor(models.Model):
CHOCOLATE = 'Chocolate'
VANILLA = 'Vanilla'
STRAWBERRY = 'Strawberry'
WALLNUT = 'Wallnut'
KULFA = 'Kulfa'
TUTYFRUITY = 'Tuttyfruity'
choices = (
(CHOCOLATE, 'chocolate scope'),
(VANILLA, 'vanilla scope'),
(STRAWBERRY, 'strawberry scope'),
(WALLNUT, 'wallnut scope'),
(KULFA, 'kulfa scope'),
(TUTYFRUITY, 'tutyfruity scope'),
)
flavor = models.CharField(max_length=20, choices=choices, null=True)
def __str__(self):
return self.flavor
now if i display the form for it, how could it be possible for user to select 1 item(or scopes) many times, and also the method i've created in IceCream model doesnt work and gives the error IceCream has no attribute flavor_set.
the view for it to display
class OrderIceCream(CreateView):
model = IceCream()
template_name = 'prac/home.html'
fields = '__all__'
template:
<h1 class="text-center mt-5">Order Ice Cream</h1>
<div class="container border-dark">
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" class="btn btn-primary mb-3 mt-3">
</form>
</div>
url is:
urlpatterns = [
path('home/<str:pk>/', IceCream.as_view(), name='home'),
path('order/<str:pk>/', OrderIceCream.as_view(), name='order-icecream'),
]
form on site image
I can get data from html but it wont save to database what should i do ?
it works correctly the only problem is that it wont be save
views.py
def comment(request , newsId):
cm = get_object_or_404(models.News , id= newsId)
print("news = " + newsId)
if request.method == 'POST' :
cm.comments_set.text = request.POST.get('comment_text')
cm.comments_set.name = request.POST.get('comment_name')
cm.save()
return HttpResponseRedirect(reverse('details', args=(cm.id,)))
urls.py
urlpatterns = [
path('', views.test),
path('details/<newsId>', views.details, name="details"),
path('comment/<newsId>' , views.comment ,name="comment")]
models.py
class News(models.Model):
title = models.CharField(max_length=300)
author = models.CharField(max_length=100)
date = models.DateTimeField()
description = models.TextField()
like = models.IntegerField(default=0)
img = models.CharField(max_length=100)
def __str__(self):
return self.title
class Comments(models.Model):
news = models.ForeignKey(News, on_delete=models.CASCADE)
name = models.CharField(max_length=100)
text = models.TextField()
def __str__(self):
return self.name
html form
<form action="{% url 'comment' newsKey.id %}" method="POST">
{% csrf_token %}
<textarea name="comment_text" id="comment_text_id" cols="30" rows="10" placeholder="Write your here comment here"></textarea>
<input type="text" name="coment_name" id="comment_name_id" placeholder="Type full name"/>
<button type="submit" value="comment_submit"> SUBMMIT </button>
</form>
What you're doing here is saving the original News object (not a Comment) after settings some random properties on the comments_set.
Basically you're shooting blanks :)
# fix this part.
news_article = get_object_or_404(models.News, id=newsId)
comment = models.Comment(
name=request.POST.get('comment_name' , ''),
text=request.POST.get('comment_text',''),
news=news_article
)
comment.save()
The comment_set is used to select all the related comments to the given News article.
See this django tutorial.
The above can also be shortened by using the create method like so:
models.Comment.objects.create(
name=request.POST['comment_name'],
text=request.POST['comment_text'],
news=news_article
)
This method also saves to the database.
I've already read many other threads complaining about this error message but I still can't figure this out. I try removing the fields that give the error, and the error message just moves to another field the next time I try to submit. They are CharField, Foreign Key, and other types.
forms.py
class TemporaryresponseForm(forms.ModelForm):
gender_custom = forms.CharField(
required=False,
label="",
)
ethnicity = forms.ModelChoiceField(
queryset=Ethnicity.objects.all(),
widget=forms.RadioSelect(),
empty_label=None,
required=True,
label="Which of the following best describes your ethnicity?"
)
...
class Meta:
model = Temporaryresponse
fields = [...'gender_custom', 'ethnicity',...]
views.py
def tr(request):
if request.method == "POST":
form = TemporaryresponseForm(request.POST)
if form.is_valid():
tempresponse = form.save(commit=False)
tempresponse.ip = "123456"
tempresponse.save()
return redirect('politicalpollingapp/index.html')
else:
form = TemporaryresponseForm()
return render(request, 'politicalexperimentpollapp/tr.html', {'form': form})
def nr(request, pk):
return render(request, 'politicalexperimentpollapp/nr.html', {'tempresponse': tempresponse})
tr.html template
{% extends 'politicalexperimentpollapp/base.html' %}
{% block extrahead %}
{% load crispy_forms_tags %}
{{ form.media }}
{% endblock extrahead%}
...
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<div><br></div>
<div class="text-center"><button type="submit" class="save btn btn-primary">CONTINUE</button></div>
</form>
..
models.py
class Ethnicity(models.Model):
ethnicity = models.CharField(max_length=200)
def __str__(self):
return '%s' % (self.ethnicity)
...
class Temporaryresponse(models.Model):
birth_year = models.PositiveIntegerField()
voting_registration = models.ForeignKey(Voting_registration, models.SET_NULL, null=True)
party_identification = models.ForeignKey(Party_identification, models.SET_NULL, null=True)
gender = models.ForeignKey(Gender, models.SET_NULL, null=True)
gender_custom = models.CharField(max_length=200, blank=True)
ethnicity = models.ForeignKey(Ethnicity, models.SET_NULL, null=True)
race = models.ManyToManyField(Race)
zip_code = models.IntegerField()
ip = models.CharField(max_length=200, blank=True)
policy_areas_of_importance = models.ManyToManyField(Policy_category, blank=True)
likelihood_of_voting = models.PositiveIntegerField(models.SET_NULL, null=True, blank=True)
Oddly no error shows up in my Chrome console - it's only because I am showing errors on the actual page. I'm not sure if that's normal. Thanks in advance for any help, I'm ripping my hair out at this point.
I discovered that I was using the wrong language for the "race" form field. I had used ModelChoiceField but it should be ModelMultipleChoiceField as follows:
race = forms.ModelMultipleChoiceField(queryset=Race.objects.all(), widget=forms.CheckboxSelectMultiple, label="5. Which of the following best describes your race? Please select all that apply.")
I have a simple form to add a website to database. This is my site model:
class Site(models.Model):
category = models.ForeignKey('Category')
category1 = models.ForeignKey('Category', related_name='+',)
subcategory = ChainedForeignKey(
'Subcategory',
chained_field='category',
chained_model_field='category',
show_all=False,
auto_choose=True)
name = models.CharField(max_length=70)
description = models.TextField()
# importuje zmienione TextFields widgets.py
keywords = MyTextField()
date = models.DateTimeField(default=datetime.now, editable=False)
url = models.URLField()
is_active = models.BooleanField(default=False)
group = models.CharField(max_length=2, choices=(('Basic',
'Basic'), ('Premium', 'Premium')))
subcategory1 = ChainedForeignKey(
'Subcategory',
chained_field='category1',
chained_model_field='category1',
related_name='subcategory1',
show_all=False,
auto_choose=True)
def get_absolute_url(self):
return "%s/%i" % (self.subcategory.slug, self.id)
class Meta:
verbose_name_plural = "Sites"
def __str__(self):
return self.name
Forms.py
class SiteAddFormFull(forms.ModelForm):
url = forms.URLField(widget=forms.TextInput(attrs={'readonly': 'readonly'}))
class Meta:
model = Site
fields = ('url', 'name', 'description', 'keywords', 'group', 'category1','subcategory1')
I would like to change my form by adding fields 'Category1', 'Subcategory1' after user choose value in group field ('Premium'). Form should reload itself and show those fields. Before choosing 'Premium' fields 'Category1', 'Subcategory1' should be invisible. How can I achieve that?
In my forms.py I added:
widgets = {'category1': forms.HiddenInput(), 'subcategory1':
forms.HiddenInput()}
In my .js file I try to show those fields but it doesn't work:
$(":hidden").show();
// $("#id_category1".show() and other posibilities
In my page soure I have
<input id="id_category1" name="category1" type="hidden" /><input id="id_subcategory1" name="subcategory1" type="hidden" />
Why it doesn't work?
You don't need HiddenInput for categories. Just hide it with jquery and show it on select change event.
<select id="group">
<option value="First">First</option>
<option value="Premium">Premium</option>
<option value="Second">second</option>
</select>
<select id="category1">
<option value="First">First</option>
<option value="Second">second</option>
</select>
Jquery
$(document).ready(function(){
$('#category1').hide();
$('#group').change(function(e) {
var group = $(this).val();
if (group == 'Premium'){
$('#category1').show();
} else {
$('#category1').hide();
}
});
});
https://jsfiddle.net/fwfm9byy/1/