How to pass request.user / user to message in Django - django

So I want to let a user message another user. I want the 'sender' field automatically to be 'request.user' and the receiver field to be the user whom the sender clicked on through their profile page. How would I go about passing those into the form?
matches.html
<div class="container">
<p>Username: {{ profile }}</p>
<h5>Your Matches:</h5>
{% for item in match %}
<br>
<p>Username: <br>{{ item.username}}</p>
<img src="{{ item.photo.url }}" width="300">
<p>Bio: <br>{{ item.description }}</p>
<br>
{% endfor %}
</div>
forms.py/InstantMessageForm
class InstantMessageForm(forms.ModelForm):
class Meta:
model = InstantMessage
fields = ('receiver','sender','message')
def save(self, commit=True):
user = super(InstantMessageForm, self).save(commit=False)
user.receiver = cleaned_data['receiver']
user.sender = cleaned_data['sender']
user.message = cleaned_data['message']
if commit:
user.save()
return user
views.py/instant_message
def instant_message(request):
if request.method == 'POST':
form = InstantMessageForm(request.POST)
if form.is_valid():
form.save()
return redirect('dating_app:home')
else:
form = InstantMessageForm()
context = {'form':form}
return render(request, 'dating_app/instant_message_form.html',context)
models.py
class InstantMessage(models.Model):
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
message = models.TextField()
class InstantMessage(models.Model):
receiver = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
sender = models.ForeignKey(settings.AUTH_USER_MODEL, related_name= 'sender',on_delete=models.CASCADE )
message = models.TextField()
instant_message_form.py
{% extends "dating_app/base.html" %}
{% load bootstrap4 %}
{% block content %}
<h1>Start chatting now!</h1>
<div class='container'>
<form method="post" action="{% url 'dating_app:instant_message' %}" >
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Register</button>
</form>
</div>
{% endblock content %}

You can create a form without the sender field:
class InstantMessageForm(forms.ModelForm):
class Meta:
model = InstantMessage
fields = ('receiver', 'message')
Then in the view, you can inject the request.user as the .sender of .instance wrapped in the form:
from django.contrib.auth.decorators import login_required
#login_required
def instant_message(request):
if request.method == 'POST':
form = InstantMessageForm(request.POST)
if form.is_valid():
form.instance.sender = request.user
form.save()
return redirect('dating_app:home')
else:
form = InstantMessageForm()
context = {'form':form}
return render(request, 'dating_app/instant_message_form.html',context)
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
In order to set the receiver, your url should for example contain the a primary key of the receiver. You can then remove the receiver from the form as well, and thus use:
from django.contrib.auth import get_user_model
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
#login_required
def instant_message(request, receiver_id):
if request.method == 'POST':
form = InstantMessageForm(request.POST)
if form.is_valid():
form.instance.sender = request.user
form.instance.receiver = get_object_or_404(get_user_mode(), pk=receiver_id)
form.save()
return redirect('dating_app:home')
else:
form = InstantMessageForm()
context = {'form':form}
return render(request, 'dating_app/instant_message_form.html',context)
You of course need then to alter the urls.py accordingly and the action url, such that it includes the primary key of the receiver.

Related

Diplay ModelForm in html

I am creating a webapp in which a user can create a project, inside each project he can answer a set of question(in my app, I call them secondquestions).
I am trying to use ModelForm to ease the creation of the form by following this guide: https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/
Howver I do not understand how I can display in my html my form.
secondquestions/views.py
def secondquestionstoanswer(request, project_id):
project = get_object_or_404(Project, pk=project_id)
if request.method == "POST":
form = SecondquestionForm(request.POST)
if form.is_valid():
form.save()
return render(request, 'secondquestions/secondquestionstoanswer.html', {'project':project})
secondquestions/models.py
from django.db import models
from django.contrib.auth.models import User
from django.conf import settings
from projects.models import Project
from django.db import models
from django.forms import ModelForm
class Secondquestion(models.Model):
second_one = models.TextField()
second_two = models.TextField()
second_three = models.TextField()
second_four = models.TextField()
second_five = models.TextField()
second_six = models.TextField()
second_seven = models.TextField()
second_eighth = models.TextField()
second_nine = models.TextField()
developer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
project = models.OneToOneField(Project, on_delete=models.CASCADE)
class SecondquestionForm(ModelForm):
class Meta:
model = Secondquestion
fields = ['second_one', 'second_two', 'second_three', 'second_four', 'second_five', 'second_six', 'second_seven', 'second_eighth', 'second_nine']
secondquestions/secondquestionstoanswer.html
{% extends 'base.html' %}
{% block title %}First set{% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
{% endblock %}
My problem:
In my html I just see the Submit button, not the form.
You never constructed a form that you passed to the template engine.
from django.shortcuts import redirect
def secondquestionstoanswer(request, project_id):
project = get_object_or_404(Project, pk=project_id)
if request.method == "POST":
form = SecondquestionForm(request.POST)
if form.is_valid():
form.instance.project = project
form.save()
return redirect('some_view')
else:
form = SecondquestionForm()
return render(
request,
'secondquestions/secondquestionstoanswer.html',
{'project':project, 'form': form}
)
With 'some_view', the name of the view to where you want to redirect in case the submission is successful.
In your <form> you specify in the action="..." attribute where what endpoint should be triggered, like:
<form method="post" action="{% url 'view_name_of_second_question' project.pk %}">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
You need a forms.py file that will contain your Model Form
secondquestions/forms.py
from django import forms
from .models import Secondquestion
class SecondquestionForm(forms.ModelForm):
class Meta:
model = Secondquestion
fields = ['second_one', 'second_two', 'second_three', 'second_four', 'second_five', 'second_six', 'second_seven', 'second_eighth', 'second_nine']

Django image:this field is required

I am trying to send a form with an image, I select the image but I always get: "this field is required" when I send the form.
here is my code:
models.py:
from django.db import models
from django.contrib.auth.models import User
class Picture(models.Model):
created_at = models.DateField(auto_now_add=True)
update_at = models.DateField(auto_now=True)
image = models.ImageField()
caption = models.CharField(max_length=50)
author = models.ForeignKey('auth.user', on_delete=models.CASCADE, related_name='pictures')
forms.py:
from django import forms
class PictureForm(forms.Form):
image = forms.ImageField()
caption = forms.CharField(max_length=50)
views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Picture
from .forms import PictureForm
from django.contrib.auth.models import User
def pictures_view(request):
pictures = Picture.objects.all()
context = {'pictures': pictures}
return render(request, 'pictures/pictures.html', context)
def picture_form_view(request):
if request.method == 'POST':
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
clean_data = form.cleaned_data()
Picture.objects.create(clean_data)
return HttpResponseRedirect('/')
else:
form = PictureForm()
return render(request, 'pictures/picture_form.html', {'form': form})
HTML:
{% extends 'pictures/base.html' %}
{% block title %}publish{% endblock %}
{% block content %}
<form class="form" action="" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
{% endblock %}
And a Little question, how can I complete the field author automaticly with the actual user?
first of all ImageField in model takes one compulsory argument upload_to so in your models
class Picture(models.Model):
###
image = models.ImageField(upload_to='upload/to/path')
###
now in your view
def picture_form_view(request):
if request.method == 'POST':
form = PictureForm(request.POST, request.FILES)
if form.is_valid():
clean_data = form.cleaned_data()
Picture.objects.create(**clean_data)
return HttpResponseRedirect('/')
else:
form = PictureForm()
return render(request, 'pictures/picture_form.html', {'form': form})
and to save current logged in user as default override form_valid()
method in Form class like
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
Try to set enctype to "multipart/form-data" in the form tag.
<form action="#" method="post" enctype="multipart/form-data">
input here ...
</form>

Using Django, how do I set a default value for a foreign key select when creating a new item

I've come to the end of the DjangoGirls tutorial and have been trying to add some extra functionality of my own
I have a new model called Subject. Each blog post now has a subject such as cookery, gardening, astrophysics, general, etc. When a blogger writes a new post, I want to force the Subject dropdown to default to 'General', but my template (post_edit.html) doesn't give me access to the SELECT so I can't set a default value
post_edit.html:
{% extends 'blog/base.html' %}
{% block content %}
<div>
<h1>New post</h1>
<form method="POST" class="post-form">{% csrf_token %}
{% if form.non_field_errors %}
<ul>
{% for error in form.non_field_errors %}
<li>{{ error }}</li>
{% endfor %}
</ul>
{% endif %}
{% for field in form %}
<div id="{{ field.auto_id }}_container"> {{ field.help_text }}
<div>
<span class="staticdata">{{ field.label_tag }}</span>
<span class="staticdata">{{ field }}</span>
</div>
<div id="{{ field.auto_id }}_errors">
{{ field.errors }}
</div>
</div>
{% endfor %}
<button type="submit" class="save btn btn-default">Save</button>
</form>
</div>
{% endblock %}
forms.py
from django import forms
from .models import Post, Subject
from django.contrib.auth.models import User
class PostForm(forms.ModelForm):
class Meta:
model = Post
fields = ('title', 'text', 'subject', 'author')
models.py
from django.db import models
from django.utils import timezone
class Post(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
subject = models.ForeignKey('Subject')
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
class Subject(models.Model):
description = models.CharField(max_length=200)
def __str__(self):
return self.description
views.py
from django.shortcuts import render, get_object_or_404
from django.shortcuts import redirect
from django.contrib.auth.models import User
from django.contrib.auth import authenticate,logout,login
from django.utils import timezone
from .models import Post, Subject
from .forms import PostForm
def post_list(request):
posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('-published_date')
return render(request, 'blog/post_list.html', {'posts': posts})
def post_detail(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'blog/post_detail.html', {'post': post})
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm()
return render(request, 'blog/post_edit.html', {'form': form})
def post_edit(request, pk):
post = get_object_or_404(Post, pk=pk)
if request.method == "POST":
form = PostForm(request.POST, instance=post)
if form.is_valid():
post = form.save(commit=False)
#... post.author = request.user
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
form = PostForm(instance=post)
return render(request, 'blog/post_edit.html', {'form': form})
def subject_list(request):
subjects = Subject.objects.all().order_by('description')
return render(request, 'blog/subject_list.html', {'subjects': subjects})
How can I set a default value for this so that the dropdown is populated with a default option when the user navigates to the page?
Try setting an initial value, in the following way
def post_new(request):
if request.method == "POST":
form = PostForm(request.POST)
if form.is_valid():
post = form.save(commit=False)
post.published_date = timezone.now()
post.save()
return redirect('post_detail', pk=post.pk)
else:
# Get the default subject.
# Perhaps you want to give your subject a name, or use an id here,
# but assuming your default subject's description is 'General' for
# this example
default_subject = Subject.objects.get(description="General")
# Set the default value
form = PostForm(initial={"subject":default_subject})
return render(request, 'blog/post_edit.html', {'form': form})

View didn't return an HttpResponse

My project is here github Project
I'm getting this error.
ValueError at /salesapp/add/ashton-aged-maduro/
The view salesapp.views.add_CartItem didn't return an HttpResponse object. It returned None instead.
I get this error when I click the 'Add to Cart' button on my singleproduct.html template which calls the ProductAddToCart form. The view is add_CartItem.
I also get the error Field is required when I don't initially set the form values. I'm just stuck now.
This is models.py
class Product(models.Model):
itemid = models.CharField(max_length=128, unique=True)
itemname = models.CharField(max_length=128)
brand = models.CharField(max_length=128)
image = models.ImageField(upload_to='static/images/')
notes = models.CharField(max_length=250)
price = models.IntegerField()
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.itemname)
super(Product, self).save(*args, **kwargs)
def __str__(self):
return self.itemname
class CartItem(models.Model):
cart_id = models.CharField(max_length=50)
date_added = models.DateTimeField(auto_now_add=True)
quantity = models.IntegerField(default=1)
itemid = models.ForeignKey('Product', unique=False)
class Meta:
db_table = 'cart_items'
ordering = ['date_added']
def name(self):
return self.product.name
My forms.py
class ProductAddToCartForm(forms.ModelForm):
cart_id = forms.CharField(max_length=50)
date_added = forms.DateTimeField()
quantity = forms.IntegerField()
slug = forms.CharField(widget=forms.HiddenInput(), required=False)
#itemid = models.ForeignKey('Product', unique=False)
class Meta:
model = CartItem
fields = ('cart_id', 'date_added', 'quantity', 'slug', 'itemid', )
My views.py
def add_CartItem(request, product_name_slug):
print('In add_CartItem --------------------')
form = ProductAddToCartForm(request.POST)
p = Product.objects.get(slug=product_name_slug)
form = ProductAddToCartForm(initial={'cart_id': 123, 'date_added':date.date.today(), 'quantity': 1, 'slug':p.slug, 'id':p.id, 'itemid':p.itemid})
form.save(commit=False)
print(form)
print(p.slug)
print(p.id)
print(p.itemid)
if form.is_valid():
print(p)
print('In form.is_valid()--------------------------------')
ci = CartItem.objects.create(cart_id=1, date_added=date.date.today(), quantity=1, itemid=p)
form.save(commit=True)
return index(request)
else:
print(form.errors) #return render(request, 'salesapp/errors.html', {'form': form})
My urls.py
from django.conf.urls import url
from salesapp import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'about/', views.about, name='about'),
url(r'customers/', views.customers, name='customers'),
url(r'products/', views.products, name='products'),
url(r'^add_product/$', views.add_product, name='add_product'),
url(r'^add_customer/$', views.add_customer, name='add_customer'),
url(r'items/(?P<product_name_slug>[\w\-]+)/$', views.show_product, name='show_product'),
url(r'^add/(?P<product_name_slug>[\w\-]+)/$', views.add_CartItem, name='add_CartItem'),
#url(r'^cart/$', views.show_cart, name='show_cart'),
#url(r'^register/$', views.register, name='register'),
#url(r'^login/$', views.user_login, name='login'),
#url(r'^logout/$', views.user_logout, name='logout'),
#url(r'^restricted/', views.restricted, name='restricted'),
]
and my template where I want to display the ProductAddToCartForm but add a product to the CartItem table.
<!DOCTYPE html>
{% extends 'salesapp/base.html' %}
{% load staticfiles %}
{% block title_block %}
{{ product.itemname }}
{% endblock %}
{% block body_block %}
<div>
<div>
<ul style="list-style:none; text-align:center;">
<li style="float:left; width:25%; margin:20px;">
<img src="/{{ product.image }}"/>
<div>
<b>{{ product.itemname }}</b><br/>
Price per cigar:<br/>
<b>${{ product.price }}</b>
<p>{{ product.notes }}</p>
</div>
<form method="post" action="/salesapp/add/{{ product.slug }}/" class="cart">
{% csrf_token %}
{% for hidden in form.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in form.visible_fields %}
{{ field.errors }}
{{ field.help_text }}
{{ field }}
{% endfor %}
<br />
<input type="submit" value="Add To Cart" name="submit" alt="Add To Cart" />
</form>
<div class="cb"></div>
</li>
</ul>
</div>
<!-- More code -->
</div>
{% endblock %}
A view function in django should either return a json or a dict or can return a Webpage
You can either do one of following
1) return a json or dict
return {"value1":"value","value2":"value"}
2)redirect to a web page
return redirect('/some/url/')
3)return Http response
return HttpResponse(status=<status code>,content="some content")
4)render a template
t = loader.get_template('myapp/index.html')
c = {'foo': 'bar'}
return HttpResponse(t.render(c, request),
content_type='application/xhtml+xml')
Because you did not return any response to the view,
According to the docs
A view function is simply a Python function that
takes a Web request and returns a Web response.
You need to return to use render method for initial rendering of form and for redirection to another view you can use redirect method of Django.
A view function must return an HttpResponse. For example, if the process was successfull and you dont want to return anything, you can return HttpResponse(status=200)
When a view handles forms, you have to split GET and POST requests. In the GET part you need to instantiate the form without data. In the POST part you fill the form with request.POST data. And this data must have ALL mandatory fields. A typical view function scheme to handle a form is the folowing:
def view(request):
if request.method == "GET":
form = MyForm()
return ...
if request.method == "POST":
form = MyForm(request.POST)
form.save()
return ...
In your template, you have to show all form fields. Then, all form fields will be passed with the request. If you dont, you need to fill the form fields in the view.
first delete the prints, almost when you make a question, are useless in Django
def add_CartItem(request, product_name_slug):
form = ProductAddToCartForm(request.POST)
if request.method == 'POST':
if form.is_valid():
ci = CartItem.objects.create(cart_id=1, date_added=date.date.today(), quantity=1, itemid=p)
ci.save()#you save your model changes, not your form
return HttpResponseRedirect(reverse('your:url'))#your return the success url or the same
else:
#here error, if form isn't valid
else:
form = ProductAddToCartForm(request.POST)
return render(request, 'your/template.html', {'form': form})
That is the correct way to work with forms in Django, first you must make a if statement asking to the browser if is a post request or a normal request, if is post request, take the data from the forms and are adding to the database, if not, Django return a empty template form.
Let me know if you problem solve

How to use django formsets to create a survey app with questions and answers?

I have a requirement to create a survey form. Different types of users will have different set of questions to answer in the survey.
models.py
from django.contrib.auth.models import Group, User
from django.db import models
ANSWER_CHOICES = (
('0', 'No'),
('1', 'Yes')
)
class Survey(models.Model):
name = models.CharField(max_length=100)
group = models.ForeignKey(Group)
def __str__(self):
return self.name
class Feature(models.Model):
name = models.CharField(max_length=150)
survey = models.ForeignKey(Survey)
def __str__(self):
return self.name
class Rating(models.Model):
rating = models.IntegerField(choices=ANSWER_CHOICES)
feature = models.ForeignKey(Feature)
rating_for = models.ForeignKey(User, related_name='rated_user')
rating_by = models.ForeignKey(User, related_name='rated_by')
def __str__(self):
return str.format("%s - %s", self.feature, self.rating)
The answer(rating) for each question(feature) is either a yes or a no represent by radio buttons. Once the user submits the form, its saves the answers in the rating table.
What is the django way of achieving this?
Thanks
forms.py
from django import forms
from django.forms import modelformset_factory, TextInput
from survey.models import Rating, Feature
class FeatureForm(forms.ModelForm):
class Meta:
model = Feature
class RatingForm(forms.ModelForm):
class Meta:
model = Rating
FeatureFormSetBase = modelformset_factory(Feature, extra=0,
widgets={'name': TextInput(attrs={'readonly': True, })}
)
class FeatureFormSet(FeatureFormSetBase):
def add_fields(self, form, index):
super(FeatureFormSet, self).add_fields(form, index)
form.fields['is_checked'] = forms.BooleanField(required=False)
survey.html
<form action="." method="post" accept-charset="utf-8">
<ul class="list-group">
{% for form in formset.forms %}
<li class="list-group-item">
<div class="hidden"> {{ form.survey }}</div>
<span> {{ form.name }} </span>
<span> {{ form.id }} </span>
<span> {{ form.is_checked }} </span>
</li>
{% endfor %}
</ul>
<p>
{{ formset.management_form }}
{% csrf_token %}
<button type="submit" name="action" value="save" class="btn btn-success">SAVE</button>
</p>
</form>
That's the code I have and it works now but I am not sure if its the best way to solve this problem? I have a lot of code in views.py to parse the post data...is there a cleaner way to achieve this?
view.py
def questionnaire(request):
q = Feature.objects.filter(survey__group=request.user.groups.all()[0]).select_related('survey')
if request.method == 'POST':
action = request.POST.get('action')
formset = FeatureFormSet(request.POST, queryset=q)
if formset.is_valid():
# iterate over all forms in the formset
for form in formset.forms:
if action == u'save':
answer = form.cleaned_data.get('is_checked')
print("Saving answer...")
rating = Rating()
rating.rating = answer
rating.feature = form.cleaned_data.get('id')
rating.rating_for = request.user
rating.rating_by = request.user
rating.save()
redirect('useraccount_dashboard')
else:
formset = FeatureFormSet(queryset=q)
return render_to_response('account_survey.html', {'formset': formset}, context_instance=RequestContext(request))
UPDATED views.py
def questionnaire(request, instance_id):
try:
instance = SurveyInstance.objects.get(pk=instance_id, completed=False)
except SurveyInstance.DoesNotExist:
raise Http404
if instance.rating_by != request.user:
return HttpResponse('Unauthorized', status=401)
q = Feature.objects.filter(survey=instance.survey)
if request.method == 'POST':
action = request.POST.get('action')
formset = FeatureFormSet(request.POST, queryset=q)
if formset.is_valid():
# iterate over all forms in the formset
for form in formset.forms:
if action == u'save':
answer = form.cleaned_data.get('is_checked')
print("Saving answer...")
rating = Rating()
rating.rating = answer
rating.feature = form.cleaned_data.get('id')
rating.survey_instance = instance
rating.save()
instance.completed = True
instance.save()
messages.add_message(request, messages.INFO, 'Thank you for your feedback.')
return redirect('useraccount_dashboard')
else:
formset = FeatureFormSet(queryset=q)
return render_to_response('account_survey.html', {'formset': formset}, context_instance=RequestContext(request))
Try using form.save() instead of creating the Rating object, filling in it's fields and then saving.