Link Username To Post Created By User - python

I would like to link the user who created the post by their username that way people know who it was posted by but I can't seem to get it to work and yes I am logged in and I have a working register and login form already.
Every time I go to submit some news from the form when logged in I get this error NOT NULL constraint failed: news_news.author_id
models.py
from django.db import models
from django.contrib.auth.models import User
from markdownx.models import MarkdownxField
from markdownx.utils import markdownify
from taggit.managers import TaggableManager
class News(models.Model):
author = models.ForeignKey(User, unique=True, on_delete=models.CASCADE)
title = models.CharField(max_length=150)
short_desc = models.CharField(max_length=500)
content = MarkdownxField()
tags = TaggableManager()
slug = models.SlugField(unique=True)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
def __str__(self):
return self.title
views.py
from django.shortcuts import render, redirect, get_object_or_404
from .models import Category, News
from .forms import NewNewsForm
from django.shortcuts import render
def show_news_view(request):
news = News.objects.values('author', 'title', 'short_desc', 'tags', 'created_at', 'updated_at')
context = {
'news': news
}
return render(request, "news/news_home.html", context)
def new_news_form_view(request):
if request.method == "POST":
form = NewNewsForm(request.POST or None)
if form.is_valid():
form.save()
form = NewNewsForm()
return redirect('/news')
else:
form = NewNewsForm()
context = {
'form': form
}
return render(request, "news/news_form.html", context)
EDIT:
forms.py
from django import forms
from .models import News
class NewNewsForm(forms.ModelForm):
class Meta:
model = News
fields = ['title', 'short_desc', 'content', 'category', 'tags', 'slug']
news_form.html
{% extends "base.html" %}
{% block content %}
{% if user.is_authenticated %}
<form action="" method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% else %}
<p>Please login before you can submit a news story.</p>
{% endif %}
{% endblock content %}

You are not passing the user.
Later edit with a simpler solution:
Simply pass commit=False when saving the form. Which will create your News object without commiting it to DB. Simply set the author afterwards and save the object.
def new_news_form_view(request):
if request.method == "POST":
form_data = request.POST or None
form = NewNewsForm(form_data)
if form.is_valid():
news = form.save(commit=False)
news.author = request.user
news.save()
return redirect('/news')
else:
form = NewNewsForm()
context = {
'form': form
}
return render(request, "news/news_form.html", context)

Related

Django database relation

I am working on a forum using django, I have a problem accessing user fullname and bio, from a model class I have. I have no problem accessing the user.username or user.email, but not from the Author class..
This is from the models.py in the forum app
User = get_user_model()
class Author(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
fullname = models.CharField(max_length=40, blank=True)
slug = slug = models.SlugField(max_length=400, unique=True, blank=True)
bio = HTMLField()
points = models.IntegerField(default=0)
profile_pic = ResizedImageField(size=[50, 80], quality=100, upload_to="authors", default=None, null=True, blank=True)
def __str__(self):
return self.fullname
My form is in the user app, where i have a profile update site, and the form is like this
from forums.models import Author
class UpdateForm(forms.ModelForm):
class Meta:
model = Author
fields = ('fullname', 'bio', 'profile_pic')
Then here is some of the update site, however nothing let me get access to the bio or fullname, I've tried so many combos. and I am lost here..
{% block content %}
<section class="section" id="about">
<!-- Title -->
<div class="section-heading">
<h3 class="title is-2">Hey {{ user.username }}</h3>
<div class="container">
<p>{{ user.bio }}bio comes here</p>
</div>
</div>
Here is the view.py from the user app
from .forms import UpdateForm
def update_profile(request):
context = {}
user = request.user
instance = Author.objects.filter(user=user).first()
if request.method == 'POST':
form = UpdateForm(request.POST, request.FILES, instance=user)
if form.is_valid():
form.instance.user = user
form.save()
return redirect('/')
else:
form = UpdateForm(instance=user)
context.update({
'form': form,
'title': 'update_profile',
})
return render(request, 'register/update.html', context)
The form html
<form method="POST" action="." enctype="multipart/form-data">
{% csrf_token %}
{{form|crispy}}
<hr>
<button class="button is-block is-info is-large is-fullwidth">Update <i class="fa fa-sign-in" aria-hidden="true"></i></button>
</form>
If there is some relation i am missing please help
Your view currently creates a new Author record each time you "update" the model. I would advise to first clean up the database and remove all authors.
Then you can convert the ForeignKey into a OneToOneField here: that way we know that each user has at most one Author:
from django.conf import settings
class Author(models.Model):
user = models.OneToOneField(
settings.AUTH_USER_MODEL,
on_delete=models.CASCADE
)
# …
Now we can alter the view to create a record in case there is no such record, or update an existing record if there is one:
from .forms import UpdateForm
def update_profile(request):
context = {}
user = request.user
instance = Author.objects.filter(user=user).first()
if request.method == 'POST':
form = UpdateForm(request.POST, request.FILES, instance=instance)
if form.is_valid():
form.instance.user = user
form.save()
return redirect('/')
else:
form = UpdateForm(instance=instance)
context.update({
'form': form,
'title': 'update_profile',
})
return render(request, 'register/update.html', context)
In the template, you can render data of the related Author model for a user user with:
{{ user.author.fullname }}
{{ user.author.bio }}

Model form data not showing up in database. Form not saving data

The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to save into the database. Instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that is being entered is being saved anywhere? This is extremely confusing considering that I've done everything correctly.
ps. I've connected my database, ran migrations and created a superuser as well but still nothing.
models.py
from django.db import models
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import AppsForm
from .models import Appear
def AppS(request):
if request == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
def results(request):
return render(request, 'Results.html')
AppsForm.html
<body>
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
Two Correction :
First : In AppsForm.html
<form action="" method="POST">
Provide a url to your form, where it should submit data
<form action="{% url 'url_name_for_Apps_view' %}" method="POST">
Second : In AppS view
This should be
if request == 'POST':
if request.method == 'POST':

Cannot get data into my database using django model forms

The form I created is not inserting the data into my database table. As far as I can tell I've done everything correctly but it still refuses to do so instead it "post" in the console and clears the form fields without creating nothing in the database. None of the data that entered is saved anywhere? Here are the files below hopeful someone can see something I'm missing.
ps. I've connected my database, ran migrations and created a superuser as well but still nothing.
models.py
from django.db import models
Media_Choices = (
("TV", "TV"),
("Radio", "Radio"),
("Youtube", "Youtube"),
("Podcast", "Podcast"),
)
class Appear(models.Model):
Show = models.CharField(max_length=100)
Media = models.CharField(max_length=30, blank=True, null=True, choices=Media_Choices)
Episode = models.IntegerField()
Date = models.DateField(max_length=100)
Time = models.TimeField(auto_now=False, auto_now_add=False)
Producer = models.CharField(max_length=100)
Producer_Email = models.EmailField(max_length=254)
def __unicode__(self):
return self.Show + ' ' + self.Producer_Email
forms.py
from django import forms
from django.core.exceptions import ValidationError
from django.forms import ModelForm
from .models import Appear
class AppsForm(ModelForm):
class Meta:
model = Appear
fields = '__all__'
def clean_Producer_Email(self):
Producer_Email = self.cleaned_data.get('Producer_Email')
if (Producer_Email == ""):
raise forms.ValidationError('field cannot be left empty')
for instance in Appear.objects.all():
if instance.Producer_Email == Producer_Email:
raise forms.ValidationError('Please fill in correct email')
return Producer_Email
views.py
from django.shortcuts import redirect, render
from django.http import HttpResponse
from .forms import AppsForm
from .models import Appear
def AppS(request):
if request == 'POST':
form = AppsForm(request.POST)
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
form = AppsForm()
return render(request, 'AppsForm.html', {'form': form})
def results(request):
return render(request, 'Results.html')
AppsForm.html
<body>
{% extends 'base.html' %}
{% block content %}
{% load crispy_forms_tags %}
<form action="" method="POST">
{% csrf_token %}
{{ form|crispy }}
<input type="submit" value="submit">
</form>
{% endblock %}
enter code here
You might be missing form errors due to which the form is not saving. Try printing if there are any form errors.
if form.is_valid():
Apps = form.save(Commit=False)
Apps.save()
else:
print(form.errors)

Django forms are not saving any information

So I have been trying to build a manager of activities with django and I'm still on the scratch. I was trying to test if the code can simply show if a acitivity is done or not, but it don't change anything. Everything looks good to me and I don't know if the error is in the form, in the view that saves the form or in anything else. I already tried to change the widget and fields of form and haven't been succeed in it.
models.py:
from django.db import models
from django.contrib.auth.models import User
class Activity(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=30)
is_complete = models.BooleanField()
def __str__(self):
return self.title
forms.py:
from .models import Activity
class ActivityUpdateForm(ModelForm):
class Meta:
model = Activity
fields = ['is_complete']
views.py:
from .models import Activity
from .forms import ActivityUpdateForm
def home(request):
acts = Activity.objects.all()
if request.method == 'POST':
form = ActivityUpdateForm(request.POST, instance=request.user)
if form.is_valid():
form.save()
return redirect('home')
else:
form = ActivityUpdateForm()
context = {
'acts': acts,
'form': form,
}
return render(request, 'diary/home.html', context)
template:
{% for act in acts %}
<form method="POST">
{% csrf_token %}
<p>{{ act.title }}</p>
<p>Is complete: {{ act.is_complete }}</p>
{{ form }}
<p>{{ act.author }}</p>
<button type="submit">Submit</button>
</form>
{% endfor %}```
This is not elegant, but you just might need to do this:
data = Activity.objects.get(author=request.user)
data.is_complete = form.cleaned_data["is_complete"]
data.save()
Please delete form.save() and write the code above.
i'm not sure if this works, but please give it a try.

I am try to get object of the logged in user in django? This list that is been created while form.save of the user that is logged in

Hello as I posted here before I new to django python need some help on how to get objects of a user that is currently logged in. I have an app named stores which contains a models named Store. I just want to gather the list of stores a user created. Do I have to add anything in setting.py ?
I am really confused about it I also tried request.user and tried to filter the object but I wasn't able to do it. I am posting my code over here kindly look into it and do let me know.
Do let me know if you need anything else to understand.
views.py of stores app
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from .forms import NewStore
from .models import Store
def store(request):
form = NewStore()
if request.method == 'POST':
form = NewStore(request.POST)
if form.is_valid():
form = form.save()
return redirect('stores_list')
else:
form = NewStore()
return render(request, "default/store.html", {'form': form})
#login_required()
def stores_list(request):
my_stores = Store.objects.all()
print(my_stores)
return render(request, "default/stores_list.html", {'my_list': my_stores})
models.py of stores app
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Store(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField(max_length=30)
lat = models.DecimalField(max_digits=50, decimal_places=20)
long = models.DecimalField(max_digits=50, decimal_places=20)
type = models.CharField(max_length=30)
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.name
stores_list.html
{% extends 'default/base.html' %}
<html>
<head><title>E-Commerce App</title></head>
{% block content %}
<h1>Welcome to your profile</h1>
<h2>Stores List</h2>
<p>This is your store list</p>
<ul>
{% for s in my_list %}
<li> Store {{ s.id }}: {{ s.name }} </li>
{% endfor %}
</ul>
{% endblock %}
</html>
Change this
if request.method == 'POST':
form = NewStore(request.POST)
if form.is_valid():
form = form.save()
return redirect('stores_list')
to
if request.method == 'POST':
form = NewStore(request.POST)
if form.is_valid():
entry = form.save(commit=False)
# Attach logged-in user details with the 'store' entry
entry.user = request.user
entry.save()
return redirect('stores_list')
To get the store list, created under the logged in user, use
logged_in_user = request.user
store_list = Store.objects.filter(user=logged_in_user)
You need to filter all stores for those belonging to the current user:
#login_required()
def stores_list(request):
my_stores = Store.objects.all().filter(user=request.user)
print(my_stores)
return render(request, "default/stores_list.html", {'my_list': my_stores})

Categories

Resources