django filters form not showing
it is supposed to show a form but only shows the submit button
models.py:
class Profile(models.Model):
user = models.OneToOneField(User,on_delete=models.CASCADE,null=True)
bio = models.TextField()
phone_number = models.IntegerField(blank=True, null=True)
Birth_date = models.DateField(blank=True, null=True)
age = models.IntegerField(blank=True, null=True)
education = models.TextField(blank=True, null=True,max_length=45)
WorkType = models.CharField(blank=True, null=True,max_length=150)
desired_wage = models.IntegerField(blank=True, null=True)
location = models.CharField(blank=True, null=True,max_length=25)
gender = models.PositiveSmallIntegerField(blank=True, null=True,choices=GENDER_CHOICES)
def __str__(self):
return str(self.user) if self.user else ''
views:
def ListingsPage(request):
Profile = Profile.objects.all()
profile_filter = ProfileFilter(request.GET,queryset=Profile)
profile = profile_filter.qs
context = {
"filter":profile_filter,
"profile":Profile,
}
return render(request,"base/Listings.html",context)
filters.py:
import django_filters
from .models import Profile
class ProfileFilter(django_filters.FilterSet):
class Meta:
model = Profile
fields = ['bio','location']
tempmlate:
<div>
<form method="GET" action="{% url 'listings' %}">
{{filter.form}}
<button type="submit" value="Submit">Submit</button>
</form>
</div>
It's supposed to show a form, it doesn't
You have typo mistake in profile queryset like this...
you need to write Profile instead of profile
def ListingsPage(request):
Profile = Profile.objects.all()
profile_filter = ProfileFilter(request.GET,queryset=Profile)
Profile = profile_filter.qs # <--------- this correction need
context = {
"filter":profile_filter,
"profile":Profile,
}
return render(request,"base/Listings.html",context)
Related
Am actually new to programming, so i am just getting a blank page, no errors.
This is my model
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile',
blank=True, null=True)
bio = models.TextField(max_length=500, null=True)
location = models.CharField(max_length=30, null=True)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse('outcome:userprofile-detail', kwargs={'pk': self.pk})
class Post(models.Model):
text = models.TextField(max_length=255)
profile = models.ForeignKey('Profile', null=True, on_delete = models.CASCADE, related_name='create')
overview = models.CharField(max_length=255)
def __str__(self):
return self.text
The view
class Userlist(LoginRequiredMixin, ListView):
model = Profile
template_name = 'outcome/user-list.html'
class UserDetail(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'outcome/userprofile_detail.html'
The template
{% for i in post.profile_set.all %}
**`trying to loop over the post`**
{{i.text}}
{% endfor %}
I have tried this for a while now and i dont know whether its from template or view.
You can override get_context_data method like this :
class UserDetail(LoginRequiredMixin, DetailView):
model = Profile
template_name = 'outcome/userprofile_detail.html'
def get_context_data(self, **kwargs):
# Call the base implementation first to get a context
context = super().get_context_data(**kwargs)
# Add in a QuerySet of the user posts
all_posts = Post.objects.all()
user_posts = all_posts.filter(profile_id=self.request.user.profile.id)
context['user_posts'] = user_posts
return context
user_detail.html
{% for post in user_posts %}
{{post.text}}
{{post.overview}}
{% endfor %}
the problem that I have is that my Model Form is not uploading a file, I had it working and after adding more code now is not working, this is what it happens: It uploads/save all the other fields except for the file, the strange thing is that if I do it from the admin site it does work. I will add that is not writing the path in the database column.
models.py
class Polizas(models.Model):
nombre = models.CharField(max_length=30, blank=True, null=True)
numero = models.CharField(max_length=30, unique=True)
aseguradora = models.CharField(max_length=20, blank=True, null=True)
carro = models.ForeignKey(
Carros, on_delete=models.CASCADE, blank=True, null=True)
inicio_poliza = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
fin_poliza = models.DateField(
auto_now=False, auto_now_add=False, blank=True, null=True)
documento = models.FileField(upload_to='polizas/', blank=True, null=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = "Polizas"
ordering = ['nombre']
def __str__(self):
return self.nombre
def get_absolute_url(self):
return reverse('polizas')
forms.py
class PostPolizas(forms.ModelForm):
class Meta:
model = Polizas
fields = ('nombre', 'numero', 'aseguradora', 'carro', 'inicio_poliza',
'fin_poliza', 'documento')
widgets = {'inicio_poliza': forms.DateInput(attrs={'type': 'date'}),
'fin_poliza': forms.DateInput(attrs={'type': 'date'})
}
views.py
class PolizaCreate(LoginRequiredMixin, CreateView):
login_url = '/login/'
redirect_field_name = 'redirect_to'
form_class = PostPolizas
template_name = "add_insurance.html"
Terminal
[06/May/2020 22:32:17] "POST /insurance/add/ HTTP/1.1" 200 4557
[06/May/2020 22:32:25] "POST /insurance/add/ HTTP/1.1" 302 0
I have tried to validate the form and it is not working, this is error is happening in my other model forms that upload files, it uploads the text fields and dates but not the files.
Try adding enctype="multipart/form-data" like this:
<form enctype="multipart/form-data" method="post">
{% csrf_token%}
<table> {{form}} </table>
<input type="submit" value="Post">
</form>
in the template form.
By default forms only pass request.POST since you are uploading a file you have to pass request.FILES into the form's constructor
Follow: https://docs.djangoproject.com/en/2.2/topics/http/file-uploads/
I have the view which displays all transactions. I have a table with contractors and I want to display all rows from this table in the options to <select>. How can i do this?
My view:
class TransactionView(CustomPermissionRequired, ListView):
# Переопределение из MultipleObjectMixin
model = Transaction
context_object_name = 'transactions'
paginate_by = 20
login_url = '/'
permission_required = (
'registration2.can_see_payments',
)
# Переопределение из TemplateResponseMixin
template_name = 'payments.html'
search_fields = [
('contractor_name', 'deal__service__contractor__name__icontains'),
('from_pay_date', 'payment_date__gte'),
('to_pay_date', 'payment_date__lte'),
('tr_id', 'id__icontains')
]
# Переопределение из MultipleObjectMixin
def get_queryset(self):
print('get_def')
filter_args = []
filter_kwargs = {}
for sf in self.search_fields:
if sf[0] is not None:
sf_value = self.request.GET.get(sf[0])
if sf_value:
filter_kwargs[sf[1]] = sf_value
return Transaction.objects.all().select_related('currency',
'payment_source__payment_type',
'deal__service__contractor'
).filter(*filter_args, **filter_kwargs).order_by('-id')
def get_context_data(self, **kwargs):
context = super(TransactionView, self).get_context_data(**kwargs)
for sf in self.search_fields:
if sf[0] is not None:
context[sf[0]] = self.request.GET.get(sf[0])
return context
My models Transaction and Contractors:
class Transaction(models.Model):
id = models.BigIntegerField(blank=True, null=False, primary_key=True)
currency = models.ForeignKey(Currency, null=True, on_delete=models.CASCADE)
deal = models.ForeignKey(Deal, null=True, on_delete=models.CASCADE)
# service_instance = models.ForeignKey(ServiceInstance, null=True, on_delete=models.CASCADE)
payment_source = models.ForeignKey(PayerPaymentSource, null=True, on_delete=models.CASCADE)
payment_date = models.DateTimeField(blank=True, null=True)
amount = models.IntegerField(blank=True, null=True)
status = models.CharField(max_length=255, blank=True, null=True)
context = models.TextField(blank=True, null=True)
class Contractors(models.Model):
id = models.IntegerField(blank=True, null=False, primary_key=True)
name = models.CharField(max_length=255, blank=True, null=True)
You don't show your HTML, but you start from a queryset to get the contractor names and ids.
contractors = Contractors.objects.all().order_by('name').values_list('id, 'name')
If you look at list(contractors) you will see it is a list of 2-tuples as required for choices.
You can use it as such if you dynamically build a form, or you can pass it to your template and iterate through it there to build an options list
{% for c in contractors %} <option ... {{c.0}} ... {{c.1}} ... {% endfor %}
There's also forms.ModelChoiceField which IIRC accepts a queryset (without values_list()) as an argument, and returns the selected [Contractor] instance as its entry in form.cleaned_data.
I have a class based view. I am trying to save an object with it's association. I have the following error :
NOT NULL constraint failed: boxes_suggestion.box_id
More explanation: I have a SuggestionBox (Model) and each Participant could add Comments into it. it's sort of a doodle clone.
detail.html
<h3>{{box.title}}</h3>
<form action="." method="post">{% csrf_token %}
{{ form.as_p }}
<input id="box_id_value" type="hidden" name="box_id_value" value='{{box.id}}' />
<input type="submit" class="btn btn-info" value="Add suggies 1" />
</form>
views.py
class SuggiesForm(FormView):
'''
Display the form
Otherwise
Process the form
1-Get the suggestion_box_id
2-Save the comment associated with that suggestion box.
'''
template_name = 'boxes/detail.html'
form_class = SuggestionForm
success_url = '/boxes/success'
box_instance = ''
def get_context_data(self, **kwargs):
'''
Retrieve the id of the Suggestion Box
'''
context = super(SuggiesForm, self).get_context_data(**kwargs)
#Find The appropriate Box so that user can add Suggies
context['box'] = Box.objects.get(pk=self.kwargs['pk'])
box_instance = context['box']
return context
def form_valid(self, form):
'''
'''
form.save(commit=False)
#box = box_instance
form.box = Box.objects.first()
form.participant = Suggestion.objects.first()
form.save()
return super(SuggiesForm, self).form_valid(form)
models.py
#python_2_unicode_compatible
class Box(models.Model):
"""
Box model
"""
def __str__(self):
return self.title
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
title = models.CharField(max_length=40, blank=True, null=True)
identify = models.BooleanField(default=False)
activate = models.BooleanField(default=False)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
#expiration_date = models.DateField(auto=Date in Future, blank=True, null=False)
#slug = AutoSlugField(_('slug'), populate_from="id")
#url(slug)
#python_2_unicode_compatible
class Participant(models.Model):
"""
Participant Model
"""
def __str__(self):
return self.email
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
email = models.EmailField(blank=True, null=True, default='anonymous#email.com')
username = models.CharField(max_length=40, blank=True, null=True)
box = models.ForeignKey(Box, on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
#python_2_unicode_compatible
class Suggestion(models.Model):
"""
For adding comments (or suggestions)
"""
def __str__(self):
return self.comment[0:10]
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
comment = models.CharField("",max_length=250, blank=True, null=True)
box = models.ForeignKey(Participant, on_delete=models.CASCADE)
created_at = models.DateField(auto_now_add=True)
updated_at = models.DateField(auto_now=True)
You correctly used commit=False, but then added the attributes onto the form object itself instead of the object returned from the save. It should be:
object = form.save(commit=False)
object.box = Box.objects.first()
object.participant = Suggestion.objects.first()
object.save()
I have a template based view that doesn't seem to be working(or atleast doesnt seem to be working on the page that needs to render it).
Here is the View:
class LocationManager(View):
template_name = "dash/LocationManager.html"
def get(self, request, *args, **kwargs):
try:
user = User.objects.get(username=request.user.username)
locations = user.get_profile().owned_locations
return render(request, self.template_name, {'locations': locations})
except:
return render(request, self.template_name)
Here are the models that have to do with this view:
#in Location models
class Location(models.Model):
region = models.ForeignKey(Region)
manager = models.ForeignKey(User)
name = models.CharField(max_length=255)
street_address = models.TextField(blank=True)
city = models.CharField(max_length=255, blank=True)
zip_code = models.CharField(max_length=20, blank=True)
#in UserProfile models
class UserProfile(models.Model):
user = models.OneToOneField(User)
api_key = models.TextField()
pp_api_key = models.TextField(blank=True)
owned_beacons = models.ManyToManyField(
Beacon,
blank=True,
null=True,
related_name='owned_beacons'
)
owned_locations = models.ManyToManyField(
Location,
blank=True,
null=True,
related_name='owned_locations'
)
def __unicode__(self):
return u'%s' % self.user.username
And finally the template:
{% for location in locations.all %}<tr>
<td>{{location.name}}</td>
<td>{{location.street_address}}</td>
<td>{{location.zip_code}}</td>
<td>{{location.region}}
</tr>
{% endfor %}
Yet the template does not render anything in relation to the form logic(the rest of the template loads fine). No errors are raised either which is why this is making it hard for me to understand why the template logic/view isn't working properly. Any ideas would be really helpful.
Try {% for location in locations %}