Django form not sending data to admin - python

I have a form users can fill out to reserve a table at a restaurant. However when they submit the form no data gets sent to the admin side.
I have watched some tutorials and read other posts on this site and nothing seems to fix it. I feel like it is something so small but I just cant figure it out.
views.PY
from django.shortcuts import render, get_object_or_404
from django.views import generic, View
from .models import Book
from .forms import BookForm
from django.http import HttpResponseRedirect
def Book(request):
"""
Renders the book page
"""
if request.user.is_authenticated:
form = BookForm(request.POST or None)
context = {
"form": form,
}
else:
return HttpResponseRedirect("accounts/login")
book_form = BookForm(data=request.POST)
if book_form.is_valid():
instance = book_form.save(commit=False)
instance.save()
else:
book_form = BookForm()
return render(
request,
"book.html",
{
"book_form": BookForm(),
}
)
models.py
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MinValueValidator
from cloudinary.models import CloudinaryField
class Book(models.Model):
name = models.CharField(max_length=50)
number_of_guests = models.PositiveIntegerField(validators=[MinValueValidator(1)])
date = models.DateTimeField()
email = models.EmailField()
requests = models.TextField(max_length=200)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
approved = models.BooleanField(default=False)
class Meta:
ordering = ['date']
def __str__(self):
return f"{self.date} for {self.name}"
forms.py
from .models import Book
from django import forms
class BookForm(forms.ModelForm):
class Meta:
model = Book
fields = (
'name',
'number_of_guests',
'date',
'email',
'requests',
)

Try this view:
from django.contrib.auth.decorators import login_required
from django.shortcuts import redirect,render
#login_required(login_url="accounts/login")
def Book(request):
if request.method=="POST":
book_form = BookForm(request.POST)
if book_form.is_valid():
book_form.save()
return redirect("some_success_page")
else:
return redirect("some_error_page")
else:
book_form = BookForm()
return render(
request,
"book.html",
{
"book_form": book_form,
}
)
In settings.py
LOGIN_URL="accounts/login"

Related

django forms post request raising an error on __init__ method

I have a django form which takes a paramater from the view to initialize the MultipleChoiceField based on the user instance.
The form is working fine when loading the template.
when i submit the form the init method in the form raising an error.
My Model models.py
from django.db import models
from django.contrib.auth.models import User
class Group(models.Model):
group_name = models.CharField('Group name', max_length=50)
def __str__(self):
return self.group_name
class GroupMembers(models.Model):
group_name = models.ManyToManyField(Group)
members = models.ForeignKey(User, on_delete=models.CASCADE)
class Transactions(models.Model):
bill_type = models.CharField('Bill type',max_length=200)
added_by = models.ForeignKey(GroupMembers, on_delete=models.CASCADE)
added_to = models.ForeignKey(Group, on_delete=models.CASCADE)
purchase_date = models.DateField(auto_now=True)
share_with = models.CharField('Share among',max_length=250)
amount = models.IntegerField(default=0)
def __str__(self):
return self.bill_type
forms forms.py
from django import forms
from .models import Transactions, GroupMembers
class Bill_CreateForm(forms.ModelForm):
def __init__(self, user_list, *args, **kwargs):
super(Bill_CreateForm, self).__init__(*args, **kwargs)
self.fields['share_with'] = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple,choices=tuple([(name, name.members) for name in user_list]))
class Meta:
model = Transactions
fields = (
'bill_type',
'amount',
'added_by',
'added_to',
'share_with',
)
** RESOLVED MY ISSUE WITH THE HELP OF #Alasdair "
EDITED SOLUTION
views views.py
from django.shortcuts import render, redirect
from django.contrib.auth.models import User
from .models import Transactions, Group, GroupMembers
from .forms import Bill_CreateForm
from django.http import HttpResponse, HttpResponseRedirect
def add_bills_home(request, id=None):
user = User.objects.get(pk=id)
grpname = Group.objects.filter(groupmembers__members=user)
gm = GroupMembers.objects.filter(group_name__group_name=grpname[0])
users_list = [i for i in gm]
if request.method == 'POST':
form = Bill_CreateForm(users_list, request.POST)
if form.is_valid():
print(form.cleaned_data['share_with'])
form.save()
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
else:
form = Bill_CreateForm(users_list)
return render(request, 'bills/create_bill.html', {'form':form})
The error is
After submiting the form with data
the request.POST method returning
below data
i don't know if the request.POST method re-initializes the form with the filled data and pass it to the init method in the form.py.
Please help me with this

How can I recover a profile picture from an author in other app?

I'm creating a blog post right now and I'm new at Django. I have an avatar picture in another app(registration) and I'm trying to import and associate correctly to another app (pages). In other words, I need to recover, in the HTML, the exact avatar picture from the user who creates a post. Thanks!
models.py (registration)
from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save
def custom_upload_to(instance, filename):
old_instance = Profile.objects.get(pk=instance.pk)
old_instance.avatar.delete()
return 'profiles/' + filename
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
avatar = models.ImageField(upload_to=custom_upload_to, null=True, blank=True)
bio = models.TextField(null=True, blank=True)
link = models.URLField(max_length=200, null=True, blank=True)
class Meta:
ordering = ['user__username']
#receiver(post_save, sender=User)
def ensure_profile_exists(sender, instance, **kwargs):
if kwargs.get('created', False):
Profile.objects.get_or_create(user=instance)
models.py (pages)
from django.db import models
from ckeditor.fields import RichTextField
from django.contrib.auth.models import User
from registration.models import Profile
class Page(models.Model):
title = models.CharField(verbose_name="Título", max_length=200) # Titulo
author = models.ForeignKey('auth.User', verbose_name="autor", on_delete=models.CASCADE, null = True)
content = RichTextField(verbose_name="Contenido") # Contenido
order = models.SmallIntegerField(verbose_name="Orden", default=0) # Orden de publicacion
created = models.DateTimeField(auto_now_add=True, verbose_name="Fecha de creación") # Fecha de creacion
updated = models.DateTimeField(auto_now=True, verbose_name="Fecha de edición") # Fecha de actualizacion
class Meta:
verbose_name = "página"
verbose_name_plural = "páginas"
ordering = ['order', 'title']
def __str__(self):
return self.title
views.py (pages)
from .models import Page
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView
from django.views.generic.edit import UpdateView
from django.views.generic.edit import DeleteView
from django.urls import reverse, reverse_lazy
from .forms import PageForm
from django.shortcuts import redirect
from django.contrib.admin.views.decorators import staff_member_required
from registration.models import Profile
#Decoradores
from django.utils.decorators import method_decorator
from django.contrib.auth.decorators import login_required
# Create your views here.
class StaffRequiredMixin(object):
#method_decorator(staff_member_required)
def dispatch(self, request, *args, **kwargs):
return super(StaffRequiredMixin, self).dispatch(request, *args, **kwargs)
#method_decorator(login_required, name="dispatch")
class PageListView(ListView):
model = Page
#method_decorator(login_required, name="dispatch")
class PageDetailView(DetailView):
model = Page
# CRUD:
#method_decorator(staff_member_required, name='dispatch')
class PageCreate(CreateView):
model = Page
form_class = PageForm
success_url = reverse_lazy('pages:pages')
def form_valid(self, form):
self.post = form.save(commit=False)
self.post.author = self.request.user
self.post.save()
return super(PageCreate, self).form_valid(form)
#method_decorator(staff_member_required, name='dispatch')
class PageUpdate(UpdateView):
model = Page
form_class = PageForm
template_name_suffix = '_update_form'
def get_success_url(self):
return reverse_lazy('pages:update', args=[self.object.id]) + '?ok'
#method_decorator(staff_member_required, name='dispatch')
class PageDelete(DeleteView):
model = Page
success_url = reverse_lazy('pages:pages')
You will probably want to provide the data using get_context_data() in the PageListView or PageDetailView. Something like:
class PageDetailView(DetailView):
model = Page
def get_context_data(**kwargs):
context = super().get_context_data(**kwargs)
# Profile image has a url property, so in the template {{ profile_image.url }}
profile_image = self.object.author.user.profile.avatar
context['profile_image'] = profile_image
return context
Take care: An error can be raised if author.user.profile does not exist. You can test for the relationship with hasattr(author.user, "profile").

django rest framework error while post through json data

here is my models.py
from __future__ import unicode_literals
from django.db import models
class User(models.Model):
name = models.CharField(max_length=200)
company_name = models.ForeignKey('Company',on_delete=models.CASCADE,related_name='user')
def __str__(self):
return self.name
class Company(models.Model):
name = models.CharField(max_length=200)
phone_number = models.IntegerField(null=True,blank=True)
def __str__(self):
return self.name
class Catalog(models.Model):
name = models.CharField(max_length=200)
no_of_pcs = models.IntegerField(null=True,blank=True)
per_piece_price = models.DecimalField(null=True,blank=True,max_digits=10,decimal_places=2)
company_name = models.ForeignKey(Company,on_delete=models.CASCADE,related_name='catalog')
def __str__(self):
return self.name
Here is my serializers.py
from rest_framework import serializers
from .models import *
from django.db.models import Sum,Count
class CatalogSerializerPost(serializers.Serializer):
id = serializers.IntegerField()
name = serializers.CharField(required=False, allow_blank=True, max_length=100)
no_of_pcs = serializers.IntegerField()
per_piece_price = serializers.IntegerField()
def create(self, validated_data):
return Catalog.objects.create(**validated_data)
class CatalogSerializer(serializers.ModelSerializer):
total_pieces = serializers.SerializerMethodField()
total_price = serializers.SerializerMethodField()
class Meta:
model = Catalog
fields = ('name','no_of_pcs','per_piece_price','company_name','total_pieces','total_price')
depth = 1
def get_total_pieces(self, obj):
totalpieces = Catalog.objects.aggregate(total_pieces=Count('no_of_pcs'))
return totalpieces["total_pieces"]
def get_total_price(self, obj):
totalprice = Catalog.objects.aggregate(total_price=Sum('per_piece_price'))
return totalprice["total_price"]
here is my views.py
from __future__ import unicode_literals
from django.http import HttpResponse
from .models import *
import json
from django.http import JsonResponse, HttpResponse
from .serializers import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework import viewsets, generics
from rest_framework.decorators import api_view
#api_view(['GET', 'POST'])
def CatalogView(request):
if request.method == 'GET':
catalogs = Catalog.objects.select_related('company_name')
serializer = CatalogSerializer(catalogs, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CatalogSerializerPost(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Here is my urls.py
from django.conf.urls import url, include
from django.contrib import admin
from api.views import CatalogView
from api import views
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework import routers
router = routers.DefaultRouter()
# router.register('catalogs',views.CatalogView,'catalog')
router.register('companies',views.CompanyView)
router.register('users',views.UserView)
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'', include(router.urls)),
url(r'catalog/', CatalogView),
]
Here i am not able to post data THRIUGH JSON DATA..
Please refer the screenshot for the error..
Thanks..
here is the screen shot for error
please check this issue.
Here i am not able to post data THROUGH JSON DATA..
showing id field is required.
there are few problems with your Serializer and View both, and also the data that you are passing, Change your serializer to this
class CatalogSerializerPost(serializers.Serializer):
name = serializers.CharField(required=False, allow_blank=True, max_length=100)
no_of_pcs = serializers.IntegerField()
per_piece_price = serializers.IntegerField()
company_name_id = serializers.IntegerField() # add this field as you have a company field in the Catalog Model. and you are passing company id in the JSON.
def create(self, validated_data):
return Catalog.objects.create(**validated_data)
and pass
"company_name_id" :3 in your json
You need to mark id field as read only:
class CatalogSerializerPost(serializers.Serializer):
id = serializers.IntegerField(read_only=True)
Also it could be more simple to use ModelSerializer.

Django - Why am I getting this IntegrityError: NOT Null constraint failed: restaurants_restaurantlocation.owner_id?

I am trying to make a website where people can find restaurants and menu items based on their pickiness. Currently I am trying to do it so when I add something to the restaurants through forms I have it associated to an user but when I submit the form I get this error:
IntegrityError
NOT Null constraint failed: restaurants_restaurantlocation.owner_id
Here is my forms.py:
from django import forms
from .models import RestaurantLocation
from .validators import validate_category
class RestaurantCreateForm(forms.Form):
name = forms.CharField()
location = forms.CharField(required = False)
category = forms.CharField(required = False)
def clean_name(self):
name = self.cleaned_data.get("name")
if name == "Hello":
raise forms.ValidationError("This is an invalid name. You stubid boy.")
return name
class RestaurantLocationCreateForm(forms.ModelForm):
#email = forms.EmailField()
#category = forms.CharField(validators = [validate_category], required = False)
class Meta:
model = RestaurantLocation
fields = [
"name",
"location",
"category"
]
def clean_name(self):
name = self.cleaned_data.get("name")
if name == "Hello":
raise forms.ValidationError("This is an invalid name. You stubid boy.")
return name
My models.py:
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save, post_save
from .utils import unique_slug_generator
from .validators import validate_category
# Create your models here.
User = settings.AUTH_USER_MODEL
class RestaurantLocation(models.Model):
owner = models.ForeignKey(User)
name = models.CharField(max_length=120)
location = models.CharField(max_length=120, null=True, blank=True)
category = models.CharField(max_length=120, null=True, blank=True, validators= [validate_category])
slug = models.SlugField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
def __str__(self):
return self.name
#property
def title(self):
return self.name #obj.title
def rl_pre_save_reciever(sender, instance, *args, **kwargs):
instance.category = instance.category.capitalize()
if not instance.slug:
instance.slug = unique_slug_generator(instance)
pre_save.connect(rl_pre_save_reciever, sender=RestaurantLocation)
My views.py:
from django.db.models import Q
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.views import View
from django.views.generic import TemplateView, ListView, DetailView, CreateView
from django.utils.datastructures import MultiValueDictKeyError
from .forms import RestaurantCreateForm, RestaurantLocationCreateForm
from .models import RestaurantLocation
# Create your views here
def restaurant_createview(request):
form = RestaurantLocationCreateForm(request.POST or None)
errors = None
if form.is_valid():
# customise
# like a pre save
form.save()
# like a post save
return HttpResponseRedirect("/restaurants/")
if form.errors:
errors = form.errors
template_name = "restaurants/form.html"
context = {"form" : form, "errors" : errors}
return render(request, template_name, context)
def restaurant_listview(request):
template_name = "restaurants/restaurants_list.html"
queryset = RestaurantLocation.objects.all()
context = {
"object_list": queryset
}
return render(request, template_name, context)
class RestaurantListView(ListView):
def get_queryset(self):
slug = self.kwargs.get("slug")
if slug:
queryset = RestaurantLocation.objects.filter(
Q(category__iexact = slug) |
Q(category__icontains = slug)
)
else:
queryset = RestaurantLocation.objects.all()
return queryset
class RestaurantDetailView(DetailView):
queryset = RestaurantLocation.objects.all()
class RestaurantCreateView(CreateView):
form_class = RestaurantLocationCreateForm
template_name = "restaurants/form.html"
success_url = "/restaurants/"
If you need any other piece of code please ask, thank you
Looking at your RestaurantLocation model, you have a foreign key into the User table:
class RestaurantLocation(models.Model):
owner = models.ForeignKey(User)
By default this can't be empty (this is what "NOT null constraint" means). And indeed it looks like your form does not do anything to fill in a restaurant owner, so you will get a database constraint error when you try to commit.
"This is an invalid name. You stubid boy."
Not a very nice thing to say to your users.

Why doesn't my search function work?

I'm currently trying to implement a search functionality to my Django app. Everything works perfectly fine, until the actual search query is handled. Say, I search for "hallo". Django would the return the following error:
django.core.exceptions.FieldError
FieldError: Cannot resolve keyword 'title' into field. Choices are: adresse, arbejde, beskrivelse, email, foerste_session, fulde_navn, id, profilbillede, relateret_til_andre_klienter, tidligere_klient, vurder_sidste_session
There seems to be some sort of conflict between my form (I am using a ModelForm) and my search function. How do I go about solving my problem?
Here is my forms.py:
from django import forms
from .models import Client
class ClientForm(forms.ModelForm):
class Meta:
model = Client
fields = (
'fulde_navn',
'adresse',
'email',
'tidligere_klient',
'foerste_session',
'beskrivelse',
'arbejde',
'relateret_til_andre_klienter',
'vurder_sidste_session',
'profilbillede'
)
And here is my models.py
from __future__ import unicode_literals
from django.utils.encoding import python_2_unicode_compatible
import uuid
from django.db import models
from django.conf import settings
from django.core.urlresolvers import reverse
import os
import uuid
YESNO_CHOICES = (
(0, 'Ja'),
(1, 'Nej')
)
SESSION_CHOICES = (
(0, '1'),
(1, '2'),
(2, '3'),
(3, '4'),
(4, '5'),
)
def upload_to_location(instance, filename):
blocks = filename.split('.')
ext = blocks[-1]
filename = "%s.%s" % (uuid.uuid4(), ext)
instance.title = blocks[0]
return os.path.join('uploads/', filename)
# Create your models here.
class Client(models.Model):
fulde_navn = models.CharField('Navn', max_length=75)
adresse = models.CharField(max_length=100)
email = models.EmailField(null=True, blank=True)
tidligere_klient = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
foerste_session = models.DateField('Dato for 1. session', null=True, blank=True)
beskrivelse = models.TextField('Noter', null=True, blank=True)
arbejde = models.CharField('Arbejde', max_length=200)
relateret_til_andre_klienter = models.IntegerField(choices=YESNO_CHOICES, null=True, blank=True)
vurder_sidste_session = models.IntegerField(choices=SESSION_CHOICES, null=True, blank=True)
profilbillede = models.ImageField('Profilbillede',
upload_to='profile_pics/%Y-%m-%d/',
null=True,
blank=True)
def __unicode__(self):
return self.fulde_navn
def get_absolute_url(self):
return reverse(viewname="client_detail", args=[self.id])
And finally my views.py where my search function is located:
from django.shortcuts import render, redirect, get_object_or_404
from django.views.generic.base import TemplateView
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from django.views.generic.edit import CreateView, UpdateView
from . import models
from .forms import ClientForm
# Create your views here.
class ClientsListView(ListView):
model = models.Client
template_name = 'clients/list.html'
paginate_by = 20
class SearchListView(ClientsListView):
def get_queryset(self):
incoming_query_string = self.request.GET.get('query', '')
return models.Client.objects.filter(title__icontains=incoming_query_string)
class ClientsDetailView(DetailView):
model = models.Client
template_name = 'clients/detail.html'
def client_create(request):
if request.method == 'POST':
form = ClientForm(request.POST)
if form.is_valid():
client = form.save()
client.save()
return redirect('client_detail', pk=client.pk)
else:
form = ClientForm()
return render(request, 'clients/form.html', {'form': form})
def client_edit(request, pk):
client = get_object_or_404(models.Client, pk=pk)
if request.method == "POST":
form = ClientForm(request.POST, instance=client)
if form.is_valid():
client = form.save()
client.save()
return redirect('client_detail', pk=client.pk)
else:
form = ClientForm(instance=client)
return render(request, 'clients/form.html', {'form': form})
class ClientsUpdateView(UpdateView):
model = models.Client
template_name = 'clients/form.html'
How do I solve this problem? I want to make it so my user is able to search for clients in my list.
In this line:
return models.Client.objects.filter(title__icontains=incoming_query_string)
You are trying to check if the field titlecontains the incoming_query_string. However, your ClientForm doesn't have such field.
You should use one of the fields you listed there or add title as a field.

Categories