How to show the forms field so user can fill - django-forms

I am trying to create a form where user can create a team. I did the view, the model and the form, But, somehow the template return with only a submit button and I don't know how to solve it. Any help is of great help, thanks.
Here is the view:
def team_create_view(request):
title = 'Create'
form = TeamCreateForm(request.POST or None, request.FILES or None)
coach = get_coach(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.coach = coach
form.save()
return redirect(reverse("club", kwargs={ 'id': form.instance.id }))
context = {
'title': title,
'form': form
}
return render(request, "team_create.html", context)
Now the form:
class TeamCreateForm(forms.Form):
form = forms.CharField(widget=forms.Textarea)
class Meta:
model = Team
fields = ('form', 'name', 'logo', 'birth', 'coach', 'players')
The model:
class Team(models.Model):
name = models.CharField(max_length=200)
logo = models.ImageField(default="", blank=True, null=True)
birth = models.DateField(default="", blank=True, null=True)
coach = models.ForeignKey(User, on_delete=models.CASCADE, default="", blank=True, null=True)
players = models.ManyToManyField(User, related_name='players')
def __str__(self):
return self.name
And finally the form:

You form render is written in inside the POST method condition. So in GET method does not render.Please try this.
First Method
Here we just change render code to outside of POST method checking if condition.
def team_create_view(request):
title = 'Create'
form = TeamCreateForm(request.POST or None, request.FILES or None)
coach = get_coach(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.coach = coach
form.save()
return redirect(reverse("club", kwargs={'id': form.instance.id }))
context = {'title': title,'form': form}
return render(request, "team_create.html", context)
Second Method
Here we check if GET method.
def team_create_view(request):
title = 'Create'
form = TeamCreateForm(request.POST or None, request.FILES or None)
coach = get_coach(request.user)
if request.method == 'POST':
if form.is_valid():
form.instance.coach = coach
form.save()
return redirect(reverse("club", kwargs={'id': form.instance.id }))
elif request.method == "GET":
context = {'title': title,'form': form}
return render(request, "team_create.html", context)

Related

Django forms update instance while keep date/time unchanged

I've created a model for properties and connected it to a form. I started to render the form with template tags using {{ form.as_p }} and everything worked fine when I used my view for editing/updating an instance. But I wanted to customize my html so I manually rendered all form fields and now there is an issue when I try to update/edit a specific instance. The error says:
list_date
Enter a valid date/time
The thing is that I don't want the list_date to be able to be update by the user so I just have it as a hidden input (list_date should be the value as when the instance was created). Is it something in the html that is wrong? Can I solve this by handling it in my view funtion updateProperty?
models.py
from django.db import models
from django.utils import timezone
from accounts.models import User
class Property(models.Model):
realtor = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True, default=User)
title = models.CharField(max_length=200)
property_type = models.CharField(max_length=200)
address = models.CharField(max_length=200)
area = models.CharField(max_length=200, blank=True)
city = models.CharField(max_length=200)
county = models.CharField(max_length=200, blank=True)
municipality = models.CharField(max_length=200, blank=True)
zipcode = models.CharField(max_length=200, blank=True)
floor = models.IntegerField(blank=True)
description = models.TextField(blank=True)
price = models.IntegerField()
rooms = models.IntegerField()
square_meter = models.IntegerField()
balcony = models.BooleanField(blank=True)
elevator = models.BooleanField(blank=True)
fee = models.IntegerField(blank=True)
photo_main = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo1 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
photo2 = models.ImageField(upload_to='photos/%Y/%m/%d/', blank=True)
is_published = models.BooleanField(default=True)
list_date = models.DateTimeField(default=timezone.now, blank=True)
viewing_date = models.DateTimeField(timezone.now, null=True, blank=True)
viewing_date2 = models.DateTimeField(timezone.now, null=True, blank=True)
KOMMANDE = 'KO'
TILL_SALU = 'TS'
BUDGIVNING = 'BG'
SALD = 'SA'
PROPERTY_STATUS = [
(KOMMANDE, 'Kommande'),
(TILL_SALU, 'Till Salu'),
(BUDGIVNING, 'Budgivning'),
(SALD, 'Såld'),
]
property_status = models.CharField(
max_length=2,
choices=PROPERTY_STATUS,
default=KOMMANDE,
)
def __str__(self):
return self.title
forms.py
from django.forms import DateInput, ModelForm
from .models import Property
class PropertyForm(ModelForm):
class Meta:
model = Property
fields = '__all__'
widgets = {'list_date' : DateInput()}
views.py
from django.shortcuts import get_object_or_404, render, redirect
from .models import Property
from .forms import PropertyForm
from django.utils import timezone
def createProperty(request):
form = PropertyForm()
if request.method == "POST":
form = PropertyForm(request.POST)
print(request.POST)
if form.is_valid():
new_property = form.save(commit=False)
new_property.list_date = timezone.now()
new_property.realtor = request.user
new_property.save()
print(new_property.list_date)
return redirect('/properties/')
context = {'form':form}
return render(request, 'properties/property_form.html', context)
def updateProperty(request, pk):
property = Property.objects.get(id=pk)
form = PropertyForm(instance=property)
if request.method == "POST":
form = PropertyForm(request.POST, instance=property)
if form.is_valid():
updated_property = form.save(commit=False)
updated_property.save()
return redirect('/properties/')
context = {'form':form, 'property':property}
return render(request, 'properties/property_form.html', context)
property_form.html (only some parts)
<label for="{{ form.list_date.id_for_label }}" hidden></label>
<input type="hidden" name="{{ form.list_date.html_name }}" id="{{ form.list_date.id_for_label }}" {% if property %} value="{{ property.list_date }}" {% endif %}>
I want the list_date to be unchanged when editing and submitting the form.
I've tried to render the list_date in the hidden input as above. I'm very grateful for any solutions that will help me.

passwords is changing for all users in django rest

I have made an API for password change but it's changing the passwords for all users instead of only one user.
seriealizer code is below:
class ChangePasswordSerializer(serializers.ModelSerializer):
password1 = serializers.CharField(write_only=True, required=True, validators=[validate_password])
password2 = serializers.CharField(write_only=True, required=True)
old_password = serializers.CharField(write_only=True, required=True)
class Meta:
model = User
fields = ('old_password', 'password1', 'password2')
def validate(self, attrs):
if attrs['password1'] != attrs['password2']:
raise serializers.ValidationError({"password": "Password fields didn't match."})
return attrs
def validate_old_password(self, value):
user = self.context['request'].user
if not user.check_password(value):
raise serializers.ValidationError({"old_password": "Old password is not correct"})
return value
def update(self, instance, validated_data):
instance.set_password(validated_data['password1'])
instance.save()
return instance
view code is below:
class ChangePasswordView(generics.UpdateAPIView):
queryset = User.objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = ChangePasswordSerializer
what is wrong with this code ?
Password change is very straight forward. Django already has a form to do it. Try the below code:
#api_view(['PUT'])
#permission_classes([IsAuthenticated])
def change_password(request):
form = PasswordChangeForm(request.user, request.data)
if form.is_valid():
form.save()
serializer = UserSerializer(request.user)
return Response(serializer.data)
return Response(form.errors, status=status.HTTP_400_BAD_REQUEST)
Read this page for more information on how to build user auth methods using DRF: https://kushgoyal.com/creating-a-sceure-login-api-using-drf-token-auth/
url for this will be of this format:
url(r'change_password/', views.change_password)

AttributeError: ProjectUpdateForm object has no attribute 'completed

I'm trying to add a checkbox to a form, if true, I want it to add a row to a through model for a manytomanyfield, but I can't access the checkbox variable. Here is the form that I have added it to, and it appears as expected, so half there:
class ProjectUpdateForm(forms.ModelForm):
completed = forms.BooleanField(). # this variable here
class Meta:
model = Update
fields = [
'category',
'update'
]
Here is my view that I was hoping to deal with it:
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
print(f"================{form.completed}") # attempt to find variable
form.save()
return redirect('project-list')
else:
form = ProjectUpdateForm()
context = {
"form": form,
"object": obj
}
return render(request, 'project_portal/project_update.html', context)
This gives me the error in the title. So I now don't understand what an attribute is, I thought it was an aspect of the class represented by a variable. How can I access this checkbox variable so I can work with it please?
This is in the cleaned_data of the form:
def project_update_view(request, slug):
obj = Project.objects.get(slug=slug)
if request.method == 'POST':
form = ProjectUpdateForm(request.POST)
form.instance.project = obj
if form.is_valid():
print(form.cleaned_data['completed'])
form.save()
return redirect('project-list')

How to auto specify form value in django form

I am working with Django forms
this is my model
class Genre(models.Model):
gen_name = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published')
def __str__(self):
return self.gen_name
this is my form
class Genreform(forms.ModelForm):
class Meta:
model=Genre
fields={ 'gen_name','pub_date'}
but i want to manually assign the pub_date (i.e. user dont have to fill that)
so i did
class Genreform(forms.ModelForm):
pub_date=forms.DateTimeField(widget=forms.HiddenInput(),initial=timezone.now())
class Meta:
model=Genre
fields={ 'gen_name'}
but this is not working
this is my request handler
def create_genre(request):
#pdb.set_trace()
if request.POST:
form = Genreform(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('http://127.0.0.1:8000/playlist/home')
else:
form=Genreform()
args={}
args.update(csrf(request))
args['form'] = form
return render_to_response('playlists/add_gen.html',args)
please suggest a way to auto fill pub_date
this is the correct code
class Genreform(forms.ModelForm):
pub_date=forms.DateTimeField(widget=forms.HiddenInput(),initial=timezone.now())
class Meta:
model=Genre
fields={ 'gen_name','pub_date'}

Django Formset... saving User with field exclusion

So in this formset the first field saves & updates just fine... but when I want to add a new object, it doesn't work out so well.
#Views.py
def edit_auto(request):
car = Auto.objects.filter(user=request.user)
CarFormSet = modelformset_factory(Auto, form=AutoForm, max_num=3)
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
formset.user = request.user
formset.save()
return render_to_response('manage_users.html', {'message':'Success! The user has been updated!'}, context_instance=RequestContext(request))
else:
formset = CarFormSet(queryset=car)
return render_to_response('mycar.html', locals(), context_instance=RequestContext(request))
#forms.py
class AutoForm(forms.ModelForm):
class Meta:
model = Auto
user = Auto.user
exclude = ('user',)
Is it something in the template? If it was a single instance of the form, form.user = request.user normally saves but this doesn't. Any suggestions? Thank you for your help.
For the user-assigning step, just iterate over the formset.
...
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
for form in formset:
form.user = request.user
formset.save()
...

Resources