Good morning guys, I have a problem with a form.
My code:
models.py
class AnagraficaGenerale(models.Model):
ragionesociale = models.CharField(max_length=40, null=True, blank=True)
cf = models.CharField(max_length=40, null=True, blank=True)
piva = models.CharField(max_length=40, null=True, blank=True)
forms.py
class AnagraficaGeneraleForm(forms.ModelForm):
class Meta:
model = AnagraficaGenerale
fields = '__all__'
views.py
#login_required
def anagrafica_new(request):
if request.method == "POST":
form = AnagraficaGeneraleForm(request.POST or None)
if form.is_valid():
form.save()
return redirect('anagrafica_list')
else:
form = AnagraficaGeneraleForm()
return render(request, 'Anagrafiche/anagrafica_new.html', {'form': form})
html
{% extends 'FBIsystem/basenobar.html' %}
{%load staticfiles %}
{% block content %}
<div id="page-wrapper">
<div class="panel">
<div class="panel-body">
<h3 class="title-hero">
Nuova Anagrafica
</h3>
<form method="POST" class="form-horizontal bordered-row">
{% csrf_token %}
<div class="example-box-wrapper">
<div class="form-group">
<label class="col-sm-2 control-label" > Ragione Sociale:</label>
<div class="col-sm-6">
{{ form.ragionesociale }}
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-lg btn-block">Salva</button>
</form>
</div>
</div>
</div>
{% endblock %}
Everything seems ok but not save, if I try with {{form.as_table}} it save.
I think there is a problem with custom field but I don't know how.
whats wrong?
TY
Related
I am new at Django I want some helps. Basically,I want from users that they can select multiple images and save it, but I got like this and I don't know how to do it. I want to display the images and user can select one of them.
please help me.
models.py
class Images(models.Model):
product_image=models.ImageField(upload_to='media',null=True, blank=True)
def __str__(self):
return "{}".format (self.product_image)
class user_select(models.Model):
name = models.CharField(max_length=200, null=True, blank=True)
product_image=models.ForeignKey(Images, on_delete=models.CASCADE)
def __str__(self):
return "{}".format (self.name)
forms.py
class UserForm(forms.ModelForm):
class Meta:
model = user_select
fields = '__all__'
views.py
def home(request):
form = UserForm()
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
form.save()
context = {'form':form}
return render(request, 'home.html', {'form':form})
home.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="container mt-5">
<div class="row mt-5 mr-5">
<div class="col-md-8 mt-5">
<div class="card border border-secondary mt-5">
<div class="col-md-8 mt-5" align='center'>
<form method="POST" action="" >
{% csrf_token %}
<div class="col-md-8">
{{ form|crispy }}
</div>
</form>
<button type="submit" class="btn btn-success mt-5 mb-5">Place Order</button>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
enter image description here
im new to Django. Im creating a bidding site, where users should be able to visit a page to create a new listing (item that they are going to put up).The form that they are required to submit has a few common fields and when valid, the said form should be saved.
Problem is, my listingcreateview() is not doing that. I submit a correct form but it wont save, it just redirects to the same form page and No errors are shown.
This because the submitted form is validated as invalid every time. I know this because of the two functions i added inside listingcreateview(), the second one is called.
It was working properly before, dont know what changes messed it up. If i add in the admin interface information by hand, it is saved successfully.
views.py:
class ListingCreateView(CreateView):
model = Listing
fields = ['title', 'content', 'image', 'min_bid', 'categories']
def form_valid(self, form):
form.instance.seller = self.request.user
return super().form_valid(form)
def form_invalid(self, form):
return HttpResponseRedirect(reverse("index"))
models.py:
class User(AbstractUser):
pass
class Listing(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100)
image = models.ImageField(blank=False, upload_to='media')
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
categories = models.CharField(max_length=25, choices = category)
seller = models.ForeignKey(User, on_delete=models.CASCADE) ##
min_bid = models.FloatField(blank=False)
image_thumbnail = ImageSpecField(source='image', processors=[ResizeToFill(300, 150)], format='JPEG', options={'quality':100})
def get_absolute_url(self):
return reverse('listing-detail', kwargs={'pk': self.pk})
listing_form.html:
{% extends "auctions/layout.html" %}
{% block body %}
<h2> Create Listing </h2>
{% if message %}
<div>{{ message }}</div>
{% endif %}
{% if messages %}
<div class="alert alert-warning" role="alert">
{{ messages }}
</div>
{% endif %}
<div class="container">
<form method="POST" action="">
{% csrf_token %}
<label class="label">{{ form.title.label }}</label>
<div class="input">{{ form.title }}</div>
<label class="label">{{ form.content.label }}</label>
<div class="input">{{ form.content }}</div>
<label class="label">{{ form.image.label }}</label>
<div class="input">{{ form.image }}</div>
<label class="label">Minimal bid</label>
<div class="input">{{ form.min_bid }}</div>
<label class="label">{{ form.categories.label }}</label>
<div class="input">{{ form.categories }}</div>
<input type="submit" value="Submit">
</form>
</div>
{% endblock %}
urls.py:
path("create-listing", login_required(ListingCreateView.as_view()), name="create-listing")
Your form is invalid because form is missing
enctype="multipart/form-data" which is needed for file uploads
I'm trying to create reservation create view that allows to break down the reservation process into 3 stages for handling all the database queries and displaying relevant choices accordingly to linkage between models (Personnel Profile has many to many key on Service)
1st stage - allows user to select service
2nd stage - displays available staff members (PersonnelProfile) who are handling this service
3rd stage - displays all the free dates / times based on staff member schedule / existing reservations, POST creates the reservation
I got stuck at the 2nd stage as my form doesn't validate. I would appreciate any advise how to overcome this issue or how to handle the idea differently. Sorry for the long post :)
UPDATE
My goal is following:
1. User selects a service
2. Backend checks which personnel profiles are offering this service and returns from to select relevant user
3. Based on selected user backend checks availability (Schedule) of user, his existing reservations and returns form for date / hour selection
4. Reservation is created after user submits from with selected hour and time
I tried to do it with additional forms to split the process in stages, as I have no idea (unfortunately I'm still a newbie) how to handle such behaviour with one form and if it's possible or not. I would appreciate any tips / guidance on how to handle this.
Reservation
class Reservation(models.Model):
user = models.ForeignKey(PersonnelProfile, on_delete=models.PROTECT)
client = models.ForeignKey(ClientProfile, on_delete=models.PROTECT)
service = models.ForeignKey(Service, on_delete=models.PROTECT)
date = models.DateField()
start_time = models.TimeField()
Service
class Service(models.Model):
name = models.CharField(max_length=100)
description = models.TextField()
price = models.IntegerField()
duration = models.IntegerField()
def __str__(self):
return self.name
PersonnelProfile
class PersonnelProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
birth_date = models.DateField(default=None, null=True)
address = models.CharField(max_length=200)
services = models.ManyToManyField(Service)
image = models.ImageField(default='profile_pics/default.jpg', upload_to='profile_pics')
def __str__(self):
return f'{self.user.first_name} {self.user.last_name}'
Schedule Model
class Schedule(models.Model):
user = models.OneToOneField(PersonnelProfile, on_delete=models.CASCADE)
availability_days = models.ManyToManyField(WorkDay)
start_hour = models.TimeField()
end_hour = models.TimeField()
def __str__(self):
return f'Schedule of {self.user.user.first_name} {self.user.user.last_name}'
WorkDay Model
class WorkDay(models.Model):
day_choices = [(str(i), calendar.day_name[i]) for i in range(7)]
name = models.CharField(max_length=9, choices=day_choices, default='1', unique=True)
def __str__(self):
return self.get_name_display()
Reservation CreateView
class ReservationCreate(LoginRequiredMixin, UserPassesTestMixin, ModelFormWidgetMixin, CreateView):
model = Reservation
success_url = '/reservations'
#staticmethod
def get(request):
form = ServiceSelection()
return render(request, 'reservations/reservation_service_selection.html', context={'form': form})
#staticmethod
def post(request):
if 'service_selection' in request.POST:
form = ServiceSelection(request.POST)
if form.is_valid():
service = form.cleaned_data['select_service']
available_personnel = PersonnelProfile.objects.filter(services=service)
personnel_names = [prs.user for prs in available_personnel]
form = PersonSelection(personnel_names)
context = {
'form': form,
'service': service
}
"""
Selected service data should be saved for the 3rd stage
"""
return render(request, 'reservations/reservation_person_selection.html', context)
return HttpResponse('Service incorrect', 404)
if 'person_selection' in request.POST:
form = PersonSelection(request.POST)
if form.is_valid():
"""
Check the schedule and existing reservations
Return last form with available dates and times for service selected in stage 1
and staff member selected in 3rd stage.
3rd stage will create Reservation with all the selected details in all 3 stages
"""
return HttpResponse('Good choice', 200) #response just for tests
return render(request, 'reservations/reservation_person_selection.html', {'form': form})
def test_func(self):
if self.request.user.is_staff:
return True
return False
Forms
class ServiceSelection(forms.ModelForm):
select_service = forms.ModelChoiceField(
queryset=Service.objects.all(),
widget=forms.Select(),
empty_label='Please select a service',
to_field_name='price'
)
class Meta:
model = Service
fields = ('select_service',)
class PersonSelection(forms.ModelForm):
def __init__(self, personnel_names, *args, **kwargs):
super(PersonSelection, self).__init__(*args, **kwargs)
self.fields['user'] = forms.ChoiceField(
choices=tuple([(name, name) for name in personnel_names]),
label='Select a person'
)
class Meta:
model = PersonnelProfile
fields = 'user',
Templates :
reservation_service_selection
{% extends 'website/home.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="/media/profile_pics/default.jpg">
<div class="media-body">
<h2 class="account-heading">Select a service</h2>
</div>
</div>
</div>
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit" name="service_selection">Update</button>
<input type="button" value="Go back" class="btn btn-outline-info" onclick="history.back()">
</div>
</form>
</div>
{% endblock %}
reservation_person_selection
{% extends 'website/home.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<div class="media">
<img class="rounded-circle account-img" src="/media/profile_pics/default.jpg">
<div class="media-body">
<h2 class="account-heading">Select a person</h2>
</div>
</div>
</div>
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{% if form.errors %}
{% for field in form %}
{% for error in field.errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endfor %}
{% for error in form.non_field_errors %}
<div class="alert alert-danger">
<strong>{{ error|escape }}</strong>
</div>
{% endfor %}
{% endif %}
<fieldset disabled>
<fieldset class="form-group">
<div class="form-group">
<label for="disabledSelect">Select a service*</label>
<select id="disabledSelect" class="form-control">
<option>{{ service }}</option>
</select>
</div>
</fieldset>
</fieldset>
{{ person_form|crispy }}
<div class="form-group">
<button class="btn btn-outline-info" type="submit" name="person_selection">Update</button>
<input type="button" value="Go back" class="btn btn-outline-info" onclick="history.back()">
</div>
</form>
</div>
I have a problem which I want to help me solve.
I have a "Post" with comments included but, when I comment a "Post" the comment I made in "Post 1" appears in "Post 2" and in all "Posts" and I want to link the comment to a single post, I've been looking for solutions but I have not been able to make it work.
EDIT I ADDED MY post/models.py
class Post(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
slug = models.SlugField(unique=True)
autor = models.CharField(max_length=200)
description = models.TextField()
likes = models.PositiveIntegerField(default=0)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
files = models.FileField(upload_to=upload_location, validators=
[validate_file_extension])
post_type = models.CharField(max_length=100, choices=Book_Type_Choices)
tags = TaggableManager()
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, related_name='cooments')
user = models.ForeignKey(User, unique=False)
text = models.CharField(max_length=250)
created_date = models.DateTimeField(default=timezone.now)
approved_comment = models.BooleanField(default=False)
views.py
#login_required
def add_comment_to_post(request, pk):
post= get_object_or_404(Post, pk=pk)
if request.method == 'POST':
form = CommentForm(request.POST)
if form.is_valid():
comment = form.save(commit=False)
comment.post= post
comment.user = request.user
comment.save()
return redirect('post_detail', slug=post.slug)
else:
form = CommentForm()
return render(request, 'comments/add_comment_to_post.html', {'form':form})
my add_comment.html, this code fragment is included on my post_detail.html
<form action="{% url 'add_comment_to_post' pk=post.pk %}" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" class="btn btn-primary" value="Comentar">
</form>
my book_detail.html
<div class="container">
<div class="row">
<div class="col-md-6 comment" style="text-align: center;">
<!-- HERE IS WHERE I INCLUDE THE add_comment.html -->
{% include 'comments/add_comment_to_post.html' %}
</div>
{% for comment in comments %}
{% if user.is_authenticated or comment.approved_comment %}
<div class="col-sm-6 col-sm-offset-1">
<div class="media-body">
<div class="well well-lg">
<div class="avatar">
<img src="{{comment.user.profile.pic.thumbnail.url}}" class="img-responsive img-circle" alt="">
</div>
<h4 class="media-heading text-uppercase reviews">{{comment.user.get_full_name}} </h4>
<ul class="media-date text-uppercase reviews list-inline">
<li>{{comment.created_date}}</li>
</ul>
<p class="media-comment">
{{comment.text}}
</p>
<a class="btn btn-info btn-circle text-uppercase" href="#" id="reply"><span class="glyphicon glyphicon-share-alt"></span> Reply</a>
<a class="btn btn-warning btn-circle text-uppercase" data-toggle="collapse" href="#replyOne"><span class="glyphicon glyphicon-comment"></span> 2 comments</a>
</div>
</div>
</div>
{% endif %}
{% empty %}
<p>No hay comentarios que mostrar :(</p>
{% endfor %}
</div>
</div>
Any idea how I can make comments work? Thanks!
In the comment model try to remove the unique=False
Change
class Comment(models.Model):
user = models.ForeignKey(User, unique=False)
to
class Comment(models.Model):
user = models.ForeignKey(User) # remove unique=False
Do the above and take it from there
I work in a postproduction company, we have our media files on a server. Through the site running on a second server, the user would point to a file, perform some operations (calculating checksums for example) and save the results in the database.
I'm looking for a "best practices" example on how to use FilePathField to get the size of a file. I've read tutorials and searched in the docs, but I'm having trouble putting the pieces together for my needs.
Some relevant code (EDIT: corrected the views, #1 and #3 are printed):
models.py
class AssetTest(models.Model):
file_path = models.FilePathField(path=r"", default="")
file_name = models.CharField(max_length=250, default="")
file_size = models.IntegerField(default=0)
def __str__(self):
return self.file_path
forms.py
class AssetTestForm(forms.ModelForm):
class Meta:
model = AssetTest
fields = ("file_name", "file_size")
views.py
def asset_select(request):
if request.method == 'POST':
print("1")
form = AssetTestForm(request.POST)
if form.is_valid():
print("2")
form.save(commit=False)
form.file_name = request.FILES['file'].name
form.file_size = request.FILES['file'].size
form.save()
return HttpResponseRedirect('/assetmanage/assets/')
print("3")
else:
print("4")
form = AssetTestForm()
return render(request, 'assetmanage/asset_select.html', {'form': form})
asset_select.html
{% extends "assetmanage/base.html" %}
{% block title %}Add Asset{% endblock %}
{% block body %}
<div class="container-fluid">
<div class="row">
<div class="col-sm-12 col-md-7">
<div class="panel panel-default">
<div class="panel-body">
<form class="form-horizontal" name="asset_select" action="/assetmanage/asset/test/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label class="control-label col-sm-2">Select a file:</label>
<input type="file" name="asset_file">
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-success">Submit</button>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
In your FilePathField give the correct path name
FilePathField(path="/home/simon/",..)
cleaned_data of FilePathField will give you the exact path so using that to get the file name and file size of it...
form = AssetTestForm(request.POST)
if form.is_valid():
form.save(commit=False)
temp_file_obj = TemporaryFileUploadHandler(form.cleaned_data['file_path'])
form.instance.file_size = temp_file_obj.chunk_size
form.instance.file_name = form.cleaned_data['file_path'].split("/")[-1]
form.save()