I do not why but the line recording.component=component in my views.py does not save the component which is given as an argument and I do not understand the reason. The only think that I have in mind is that I am using smart_select. Here is what I have:
My views.py file:
def create_recording(request, slug, inspection_id, component_id):
inspection = get_object_or_404(Inspection, pk=inspection_id)
plant = get_object_or_404(Plant, slug=slug)
component=get_object_or_404(Component, pk=component_id)
if request.method == "POST":
form = RecordingForm(request.POST)
if form.is_valid():
recording = form.save(commit=False)
recording.user = request.user
recording.plant = plant
recording.inspection=inspection
recording.component=component
recording.save()
return redirect('data:inspection_detail', slug=plant.slug, inspection_id=inspection.id)
else:
form = RecordingForm()
context = {'form': form, 'plant':plant,'inspection':inspection,}
template = 'data/create_recording.html'
return render(request, template, context)
my models.py:
class Recording(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
plant = models.ForeignKey(Plant, on_delete=models.CASCADE)
inspection = models.ForeignKey(Inspection, on_delete=models.CASCADE)
component = models.ForeignKey(Component)
group = ChainedForeignKey(Group, chained_field="component", chained_model_field="component", show_all=False, auto_choose=True, sort=True)
failure = ChainedForeignKey(Failure, chained_field="group", chained_model_field="group", show_all=False, auto_choose=True, sort=True)
def __str__(self):
return str(self.failure)
my forms.py:
class RecordingForm(forms.ModelForm):
class Meta:
model = Recording
fields = ['group', 'failure',]
my html:
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=1 %}">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Chair
</button>
</a>
<a href="{% url 'data:create_recording' slug=plant.slug inspection_id=inspection.id component_id=2 %}">
<button type="button" class="btn btn-success">
<span class="glyphicon glyphicon-plus"></span> Table
</button>
</a>
and the html for for my form:
<div class = "col-sm-7">
<div class="panel panel-primary">
<div class="panel-heading">
<h4>Add new recording</h4>
</div>
<div class="panel-body">
<form method='POST'>
{% csrf_token %}
{{ form|crispy }}
<button type = 'submit' class="btn btn-success">Save</button>
</form>
</div>
</div>
</div>
and my url:
url(r'^plants/(?P<slug>[-\w]+)/inspection(?P<inspection_id>[0-9]+)/create_recording/(?P<component_id>[0-9]+)$', views.create_recording, name='create_recording'),
please let me know if I need to add some more information.
Related
I need some fresh eyes, what am I missing here? In my Post Model imageField is defined as "picture" to be uploaded on the site, I seed it on my admin panel, it gets uploaded just fine but I can't seem to make it appear on the page: http://127.0.0.1:8000/posts/. I get ValueError at /posts/
The 'picture' attribute has no file associated with it. Highlited line is line 257, in post_comment_create_view
return render(request, 'network/posts.html', context)
Model:
class Post(models.Model):
# id is created automatically by Django
picture = models.ImageField(upload_to='images', blank=True, validators=[FileExtensionValidator(['png', 'jpg', 'jpeg'])])
content = models.TextField()
liked = models.ManyToManyField(Profile, blank=True, related_name="likes")
author = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ('-created',)
def __str__ (self):
return str(self.content[:20])
Forms:
class PostModelForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea(attrs={'rows':2}))
class Meta:
model = Post
fields = ('content', 'picture')
Views:
#login_required
def post_comment_create_view(request):
qs = Post.objects.all()
profile = Profile.objects.get(user=request.user)
#Setting up pagination
p = Paginator(qs, 5)
page = request.GET.get('page')
post_list = p.get_page(page)
#Post form, comment form
p_form = PostModelForm()
c_form = CommentModelForm()
post_added = False
profile = Profile.objects.get(user=request.user)
if 'submit_pForm' in request.POST:
print(request.POST)
p_form = PostModelForm(request.POST, request.FILES)
if p_form.is_valid():
instance = p_form.save(commit=False)
instance.author = profile
instance.save()
p_form = PostModelForm()
post_added = True
if 'submit_cForm' in request.POST:
c_form = CommentModelForm(request.POST)
if c_form.is_valid():
instance = c_form.save(commit=False)
instance.user = profile
instance.post = Post.objects.get(id=request.POST.get('post_id'))
instance.save()
c_form = CommentModelForm()
context = {
'qs': qs,
'profile': profile,
'p_form': p_form,
'c_form': c_form,
'post_added': post_added,
'post_list': post_list,
}
return render(request, 'network/posts.html', context)
HTML:
{% block body %}
<div>
<div class="border border-light rounded" style="width: 25rem;">
{% if post_added %}
<div id="alertFade" class="alert alert-success" role="alert">Post added!</div>
{% endif %}
<form action="" method="POST" enctype="multipart/form-data" class="form-group">
{% csrf_token %}
{{p_form}}
<button type="submit" class="btn btn-sm btn-success" name="submit_pForm">Send Post</button>
</form>
</div>
{% for obj in post_list %}
<div class="card center" style="width: 30rem;">
<div class="card-head" style="background-color: #d0e2bc;">
<img width="50px" class="avatar img-thumbnail rounded-circle z-depth-2 ml-1" src={{obj.author.avatar.url}}> {{ obj.author.user }} - {{ obj.created|naturaltime }}
{% if request.user == obj.author.user %}
<button class="btn btn-sm btn-success float-right mt-2 mr-1">Delete</button>
<button class="btn btn-sm btn-success float-right mr-1 mt-2">Edit</button>
{% endif %}
</div>
<div class="card-body">
<img src={{obj.picture.url}}> <br>
<p class="card-text">{{obj.content|safe}}</p>
<hr>
</div>
<button class="cmt_btn ui button mb-5">show / hide comments</button>
<div class="comment-box">
{% if obj.comment_set.all %}
{% for c in obj.comment_set.all %}
<img width="20px" class="avatar img-thumbnail rounded-circle"src={{c.user.avatar.url}} alt="">
<span>{{ c.user }}</span>
<div class="mt-2">{{ c.body }}</div>
{% endfor %}
{% endif %}
There should be quotes around the src:
<img src={{obj.picture.url}}> <!-- will not work -->
Should be:
<img src="{{obj.picture.url}}"> <!-- works -->
This is for the tag attributes. For content within the tag, what you have is fine, no quotes. This is good:
<span>{{ c.user }}</span> <!-- works -->
I solved it, the solution is that I had to check if the img exists:
{% if obj.picture %}
<img src="{{obj.picture.url}}"> <br/>
{% endif %}
Registered users of my app can create and delete expense tracking sub-accounts. When deleting, they get to pick which account to delete:
The above image shows the current choices. I would like to display the name of the account, rather than the object which the name is referring to, but how?
forms.py
class UdaForm(forms.Form):
# User Deleted Account Form
def __init__(self, *args, user, **kwargs):
super().__init__(*args, **kwargs)
self.user = user
self.fields['UDA_name'].queryset = UserMadeAccount.objects.filter(UMA_user=user)
UDA_name = forms.ModelChoiceField(label="Account", queryset=UserMadeAccount.objects.all())
views.py
def user_accounts(request, user_id):
if request.user.is_authenticated:
# Get all accounts of user by matching user_id
user_made_accounts = specific_umacs(user_id)
user_data = [i for i in user_made_accounts]
if "UMA_form_name" in request.POST:
if request.method == 'POST':
uma_form = UmaForm(request.POST)
uda_form = UdaForm(user=request.user)
if uma_form.is_valid():
# Adds new user made account to the DB
add_uma(uma_form, request.user)
# Get all accounts of user by matching user_id
user_made_accounts = specific_umacs(user_id)
user_data = [i for i in user_made_accounts]
return render(request, 'user_accounts.html', {"uma_form": uma_form, "uda_form": uda_form, "user_data": user_data})
if "UDA_name" in request.POST:
if request.method == 'POST':
uda_form = UdaForm(request.POST, user=request.user)
uma_form = UmaForm()
if uda_form.is_valid():
# Delete user made account from DB
delete_uma(uda_form=uda_form, user_obj=request.user)
# Get all accounts of user by matching user_id
user_made_accounts = specific_umacs(user_id)
user_data = [i for i in user_made_accounts]
return render(request, 'user_accounts.html', {"uma_form": uma_form, "uda_form": uda_form, "user_data": user_data})
if request.method == 'GET':
uma_form = UmaForm()
uda_form = UdaForm(user=request.user)
else:
uma_form = UmaForm()
uda_form = UdaForm(user=request.user)
return render(request, 'user_accounts.html', {"uma_form": uma_form, "uda_form": uda_form, "user_data": user_data})
else:
return render(request, 'please_authenticate.html')
user_accounts.html
{% extends "base.html" %}
{% block page_content %}
...
<!-- Delete Account Modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target=".bd-delete_me-modal-lg">Delete Account</button>
<div class="modal fade bd-delete_me-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg modal-dialog-centered">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLongTitle">Delete one of your accounts</h5>
</div>
<div class="modal-body">
<form action="" method="POST">
{% csrf_token %}
<div class="form-row">
<div class="col">
{{ uda_form.UDA_name|as_crispy_field }}
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Delete</button>
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</form>
</div>
</div>
</div>
<!-- Modal END -->
...
{% endblock page_content %}
You can simply add __str__ method [doc] to your UserMadeAccount model
def __str__(self):
return self.field_name
The str() method is called whenever you call str() on an object.
Django uses str(obj) in a number of places. Most notably, to display
an object in the Django admin site and as the value inserted into a
template when it displays an object. Thus, you should always return a
nice, human-readable representation of the model from the str()
method.
I have two models child and academy by which these two models have relationship to each other
here is child models
from django.db import models
class Child_detail(models.Model):
Firstname = models.CharField(max_length = 50)
Lastname = models.CharField(max_length = 50)
Tribe = models.CharField(max_length = 50)
def __str__(self):
return self.Firstname
Here is academy model
from django.db import models
from child.models import Child_detail
class Academic(models.Model):
Student_name = models.ForeignKey(Child_detail,on_delete = models.CASCADE)
Class = models.CharField(max_length = 50)
Average_grade = models.CharField(max_length = 10)
def __str__(self):
return str(self.Student_name)
Here is my views.py file that contain edit functionality,into the template it does not show the fields to edit so i have to write those fields again and even that it does not edit anything
def edit_academy(request,pk):
child=get_object_or_404(Child_detail,pk=pk)
form = AcademicForm(instance=child)
if request.method == "POST":
form=AcademicForm(request.POST,instance=child)
if form.is_valid():
form.save()
return redirect('more',pk=pk)
context={
'form':form,
'child':child
}
return render(request,'functionality/edit.html',context)
Here is my template file
{% extends 'base.html' %}
{% load static %}
{% load crispy_forms_tags %}
{% block content %}
<section id="register" class="bg-light py-5">
<div class="container">
<div class="row">
<div class="col-md-6 mx-auto">
<div class="card">
<div class="card-header bg-primary text-white">
<h4>
<i class="fas fa-user-plus"></i> Edit {{child.Firstname | title}} {{child.Lastname | title}} Academic Details </h4>
</div>
<div class="card-body">
<form action="" method="post" autocomplete="on">
{% csrf_token %}
<div class="form-group">
{{form | crispy}}
<input type="submit" value="Save" class="btn btn-primary btn-block">
</form>
</div>
</div>
</div>
</div>
</section>
{% endblock %}
And here is my Academic form file
class AcademicForm(forms.ModelForm):
class Meta:
model=Academic
fields='Class','Date','Average_grade','Overall_position','Total_number_in_class'
labels={
'Average_grade':'Average Grade',
'Overall_position':'Overall Position',
'Total_number_in_class':'Total Number In Class'
}
Try like this:
def edit(request,pk):
child=get_object_or_404(Child_detail,pk=pk)
form = ChildForm(instance=child)
if request.method == "POST":
form=ChildForm(request.POST,instance=child)
if form.is_valid():
form.save()
return redirect('child')
context={
'form':form,
'child':child
}
return render(request,'functionality/edit.html',context)
I want to get the username using the field user (foreignkey)
I don't know how get the username in the view
model.py
class Publication(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
filters.py
class PublicationFilter(django_filters.FilterSet):
user = django_filters.CharFilter(lookup_expr='exact')
class Meta:
model = Publication
fields = ['user']
views.py
def publication_list(request):
f = PublicationFilter(request.GET, queryset=Publication.objects.all())
return render(request, 'info/filter.html', {'filter':f})
html
<h2>Lista de sus informes</h2>
<p class="profile-data">
<div class="col-md-4 mt-2 mb-3 ">
<div class="row p-1">
<div class="col-md-12">
<form action="" method="get" >
<b> {{ filter.form.as_p }} </b><br>
<button type="submit">Search</button>
</form>
<ul>
<b>{% for profile in filter.qs %} </b><br>
<b>{{ profile.nombre }} </b><br>
<b>{{ profile.user }} </b><br>
Ver perfil<br>
{% endfor %}
You can use '__' : Publication.objects.filter(user__username="John Doe")
I have a basic Form that accepts a file / image from a template. For some reason it won't validate and I can't see the error.
views.py
# Flag a Job as complete
#login_required()
#user_passes_test(lambda u: u.groups.filter(name='Developer').exists(), login_url='/login/', redirect_field_name='not allowed')
#require_http_methods(['POST'])
def job_complete(request, jobid, userid):
# Get the Job
job = Jobs.objects.get(id=jobid)
jobsubmit = JobSubmitForm(request.FILES)
if jobsubmit.is_valid():
js = jobsubmit.save(commit=False)
js.user_id = userid
js.job_id = jobid
js.save()
job.status = 'IR'
job.save()
return redirect('view_job', jobid=jobid, slug=job.slug)
else:
messages.error(request, "There are form errors!")
return redirect('view_job', jobid=jobid, slug=job.slug)
forms.py
class JobSubmitForm(forms.ModelForm):
class Meta:
model = JobSubmit
fields = ('file', 'image', 'comment', 'gitHubLink')
def save(self, commit=True):
jobsubmit = super(JobSubmitForm, self).save(commit=False)
jobsubmit.user_id = self.cleaned_data['user_id']
jobsubmit.job_id = self.cleaned_data['job_id']
if commit:
jobsubmit.save()
return jobsubmit
view.html
<form method="post" action="/job/job_complete/j{{ job.id }}/u{{ request.user.id }}/" class="form-inline btn-group" enctype="multipart/form-data">
{% csrf_token %}
<div class="span6 inline">
<label class="control-label">Attach Files: </label>{{ job_submit.file }}
<p class="help-block">Attach files that go with this Job.</p>
</div>
<div class="span6 inline">
<label class="control-label">Attach Images: </label>{{ job_submit.image }}
<p class="help-block">Attach images that go with this Job.</p>
</div>
<div class="span6 inline">
<label class="control-label">GitHub URL: </label>{{ job_submit.gitHubLink|add_class:"form-control"|attr:"placeholder:Example: https://www.github.com/path/to/code/repo/or/commit" }}
<p class="help-block">If hosting work on GitHub.</p>
</div>
<div class="span6 inline"><label class="control-label">Job Comments(Required): </label>{{ job_submit.comment|add_class:"form-control"|attr:"placeholder:Example: Fun Job! Please keep me in mind for future work!" }} </div>
<div class="modal-footer">
<button type="submit" class="btn btn-success btn-med pull-left"><i class="fa fa-check-circle"></i> Job Complete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
models.py
# Store data related to a Job (files, comments, etc.)
class JobSubmit(models.Model):
job = models.ForeignKey(Jobs)
user = models.ForeignKey(User)
file = models.FileField(upload_to="uploads/jobs/files", blank=True, null=True)
image = models.ImageField(upload_to="uploads/jobs/images", blank=True, null=True)
comment = models.TextField()
gitHubLink = models.URLField(blank=True)
Hopefully it's not something silly... it's been a long day and sleepy programming isn't the best idea. :/
Appreciate the help if anyone sees what's wrong. Pointers welcomed, as well. Cheers,
This line:
jobsubmit = JobSubmitForm(request.FILES)
should be as:
jobsubmit = JobSubmitForm(request.POST, request.FILES)
try it?