I write an app in django - sth like twitter, i have already log in/log out panel, and form when already logged in user can add a tweet.
A tweet has a 3 columns in database:
class Tweet(models.Model):
content = models.CharField(max_length=140)
creation_date = models.DateTimeField(auto_now_add=True)
user = models.ForeignKey(User, on_delete=models.CASCADE)
The form looks like:
class TweetForm(forms.Form):
content = forms.CharField(label='content')
And the view:
class TweetCreationView(LoginRequiredMixin, View):
permission_required = 'twitter.add_tweet'
raise_exception = True
permission_denied_message = 'You are not allowed being there!'
def get(self, request):
form = TweetForm()
return render(request, "twitter/add_tweet.html", {"form": form})
def post(self, request):
form = TweetForm(request.POST)
if form.is_valid():
if request.user.is_authenticated():
username = request.user.username
user_id = username.id
content = form.cleaned_data.get('content')
return render(request, "twitter/add_tweet.html", {"form": form})
How can i obtain an already logged in user in django and add his/her id to post view form?
do something similar to this. I did not check if this is working.
if request.user.is_authenticated():
if form.is_valid():
form = form.save(commit=False)
form.user = request.user
content = form.cleaned_data.get('content')
form.save()
return render(request, "twitter/add_tweet.html", {"form": form})
Ok,
I've managed to do it in kinda primitive way:
def post(self, request):
form = TweetForm(request.POST)
if form.is_valid():
t = Tweet()
current_user = request.user
t.content = form.cleaned_data.get('content')
t.user_id = current_user.id
t.save()
if t:
return redirect(reverse("base"), locals())
return render(request, "twitter/add_tweet.html", locals())
Related
I made a web app where the user can submit a form. I want the user to be able to view his submission but I can't figure out how to access the previously submitted data.
I keep getting an error related to failing to reverse match failure.
The error says
Reverse for 'submission' with no arguments not found. 1 pattern(s) tried: ['submission/(?P<application_id>[0-9]+)/$']
Views.py
#login_required
def apply(request):
"""Submit application"""
if request.method != 'POST':
form = ApplicationForm()
else:
form = ApplicationForm(data=request.POST)
if form.is_valid():
new_application = form.save(commit=False)
new_application.owner = request.user
new_application.save()
return redirect('credit_apply:submitted')
context = {'form': form}
return render(request, 'credit_apply/apply.html', context)
def submission(request, application_id):
"""View and maybe? edit application"""
application = Application.objects.get(id=application_id)
owner = application.owner
if request.method != 'POST':
form = ApplicationForm(instance=application)
else:
form = ApplicationForm(instance=application, data=request.POST)
if form.is_valid():
form.save()
return redirect('credit_apply:submitted', owner_id=owner.id)
context = {'application': application, 'owner': owner, 'form': form}
return render(request, 'credit_apply/submission.html', context)
models.py
from django.db import models
from phonenumber_field.modelfields import PhoneNumberField
from django.contrib.auth import get_user_model as user_model
User = user_model()
# Create your models here.
class Application(models.Model):
"""App para las aplicacions de credito"""
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=40)
business = models.CharField(max_length=100)
m_number = PhoneNumberField(max_length=16)
email = models.EmailField(max_length=254, unique=True)
date_added = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.first_name} {self.last_name} {self.business}"
url pattern
path('submission/<int:application_id>/', views.submission, name='submission')
base template line that is causing the error to pop up
{% if user.is_authenticated %}
<li class="nav-item">
<a class="nav-link" href="{% url 'credit_apply:submission' application.id%}">
Edita!</a></li>
....
changed my view to:
def submission(request):
"""View and maybe? edit application"""
model = Application
application = Application.objects.get(owner=request.user)
if request.method != 'POST':
form = ApplicationForm(instance=application)
else:
form = ApplicationForm(instance=application, data=request.POST)
if form.is_valid():
form.save()
return redirect('credit_apply:submitted')
context = {'application': application, 'form': form}
return render(request, 'credit_apply/submission.html', context)
removed the application_id pattern and application.id tag in template since no longer needed
I currently have an index view with several input tags for a name, file and tags.
I'm trying to connect the model that handles that view (name: Uploaded) to the User model and associate the logged in users username to the Uploaded model.
Here's my view:
def index(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
form.save()
else:
form = FileUploadForm
allTags = Tag.objects.all()
context = {'form': form, 'allTags': allTags}
return render(request, 'index.html', context)
and here's the Uploaded model:
class Uploaded(models.Model):
objects: models.Manager()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="users")
name = models.CharField(max_length=50)
file = models.FileField(upload_to=MEDIA_ROOT)
tags = TaggableManager()
def __str__(self):
return f"{self.name} {self.file}"
You can "patch" the .instance wrapped in the form with the logged in user:
from django.contrib.auth.decorators import login_required
#login_required
def index(request):
if request.method == 'POST':
form = FileUploadForm(request.POST, request.FILES)
if form.is_valid():
form.instance.user = request.user
form.save()
else:
form = FileUploadForm()
allTags = Tag.objects.all()
context = {'form': form, 'allTags': allTags}
return render(request, 'index.html', context)
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].
Im trying to create a way for people to post their ideas but is giving me this error:
NOT NULL constraint failed: blog_userpost.user_id. I want the user to have to be registered and login in order to make/read the posts.
views.py:
#create view
#login_required(login_url='login')
def userposts_create_view(request):
form= UserPostForm(request.POST or None)
if request.method == "POST":
if form.is_valid():
form = form.save()
form.save()
return HttpResponseRedirect("/Blog/posts/")
context= {'form': form,
}
return render(request, 'posts/userposts-create-view.html', context)
#list view
#login_required(login_url='login')
def userposts_list_view(request):
allposts= UserPost.objects.all()
context= {'allposts': allposts,
}
return render(request, 'posts/userposts-list-view.html', context)
#detail view
#login_required(login_url='login')
def userposts_detail_view(request, url=None):
post= get_object_or_404(UserPost, url=url)
context= {'post': post,
}
return render(request, 'posts/userposts-detail-view.html', context)
models.py
This are the categories I want the post to have, I can 'create' the post but whenever I submit it gives me the error.
User= settings.AUTH_USER_MODEL
class UserPost(models.Model):
user= models.ForeignKey(User, null=False,editable=False, verbose_name='Usuario', on_delete=models.CASCADE)
title= models.CharField(max_length=500)
content= models.TextField()
categories = models.ManyToManyField(Category, verbose_name='Categorias', blank=True,related_name="articles")
created_at = models.DateTimeField(auto_now_add=True, verbose_name='Creado el ')
updated_at = models.DateTimeField(auto_now=True, verbose_name='Actualizado el ')
def save(self, *args, **kwargs):
super(UserPost, self).save(*args, **kwargs)
forms.py
from django import forms
from .models import UserPost
class UserPostForm(forms.ModelForm):
class Meta:
model= UserPost
fields= ["title", "content","categories"]
One simple way is to use model's manager instead of form.save(). So in your condition (i.e. if form.is_valid()) you can use something like:
def userposts_create_view(request):
form= UserPostForm(request.POST or None)
if form.is_valid():
data = form.cleaned_data
categories = data.pop('categories', None)
user_post = UserPost.objects.create(**data, user=request.user)
if categories:
user_post.categories.add(*categories)
return HttpResponseRedirect("/Blog/posts/")
context= {'form': form}
return render(request, 'posts/userposts-create-view.html', context)
I do not use admin apps in Django, and I want to edit the user with form, but when I edit the groups to the users, Django doesn't save my choice and user has no groups.
views.py:
def useredit(request, pk):
user = get_object_or_404(User, pk=pk)
if request.method == "POST":
form = EditUserForm(request.POST, instance=user)
if form.is_valid():
user.save()
messages.success(request, 'Utilisateur édité avec succés !')
return HttpResponseRedirect('/user')
else:
form = EditUserForm(instance=user)
return render(request, 'compta/users/edit.html', {'form': form})
forms.py:
class EditUserForm(UserChangeForm):
class Meta:
model = User
fields = '__all__'
def save(self, commit=True):
user = super().save(commit)
self._save_m2m()
return user
You need to save form instead of user instance
replace
if form.is_valid():
user.save()
#^^^^
with
if form.is_valid():
form.save()
#^^^^
I am new to django, I an updating my userprofile models using forms and view,I need to get the current user who is logged in and I need to update the details for that user
forms.py
class ProfileForm(forms.ModelForm):
class Meta:
model = UserProfile
fields = ('gender','email_id','mobile_number','date_of_birth')
View.py
def update_UserProfile_views(request):
if request.method == "POST":
form = ProfileForm(request.POST)
if form.is_valid():
profile = form.save(commit=False)
profile.save()
else:
form = ProfileForm()
return render(request, 'base.html', {'form': form})
You can create a instance and get user name
def update_UserProfile_views(request):
try:
current_user = request.user
user = UserProfile.objects.get(user_name=current_user)
except Exception:
return render(request, 'base.html', {})
else:
if request.method == "POST":
form = ProfileForm(request.POST,instance=user)
if form.is_valid():
profile = form.save(commit=False)
profile.save()
else:
form = ProfileForm()
return render(request, 'base.html', {'form': form})