I am a beginner in django and i want to create a new web page which i can edit and add to a database model like the admin site page but this will be in the website to enable the user to control it and i can extend my base.html page in it, I search for it and i didn't find a simple solution like admin base site that enable me to control the models, i tried to send all objects of this model in the context but i cant add or edit it in the database model, just i can view it only.
can any one help me? thanks.
This is my models.py for this web page:
from django.db import models
class Email(models.Model):
type = models.CharField(max_length=200, null=True, blank=True)
subject = models.TextField()
from_email = models.CharField(max_length=200, null=True, blank=True)
to_email = models.CharField(max_length=200, null=True, blank=True)
reply_to_email = models.CharField(max_length=200, null=True, blank=True)
body_text = models.TextField()
body_html = models.TextField()
status= models.CharField(max_length=200, null=True, blank=True,default='waiting')
def __unicode__(self):
return self.to_email
class EmailTemplate(models.Model):
template_name=models.CharField(max_length=200)
subject = models.CharField(max_length=200)
from_email = models.CharField(max_length=200, null=True, blank=True)
reply_to_email = models.CharField(max_length=200, null=True, blank=True)
body_text = models.TextField()
body_html = models.TextField()
def __unicode__(self):
return self.template_name
my views.py
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template import RequestContext
from survey.models import *
from user_management.models import Candidate
from django.contrib.auth.decorators import login_required
from django import forms
import settings
from emailtemplates import models
from email_sender.models import *
from report.pdf import DrawarmPDF,send_pdf_in_email
from decorators import superuser_required
#login_required
#superuser_required()
def home(request):
query_results = EmailTemplate.objects.all()
return render_to_response('emailtemplates/emailtemplates.html',
{"query_results":query_results},
context_instance=RequestContext(request))
you need add action for POST method:
def home(request):
if request.method == 'POST':
# ^^^^^^
# do save action code
query_results = EmailTemplate.objects.all()
return render_to_response('emailtemplates/emailtemplates.html',
{"query_results":query_results},
context_instance=RequestContext(request))
And you may use forms for save action, more details here: forms view
And it be good to read about form class view class-based-views
Related
Urls.py:
urlpatterns = [
path("", views.index, name="blogHome"),
path("blogpost/<int:id>/", views.blogpost, name="blogHome")
]
Views.py:
django.shortcuts import render
from .models import Blogpost
# Create your views here.
def index(request):
return render(request, 'blog/index.html')
def blogpost(request, id):
post.Blogpost.objects.filter(post_id = id)[0]
print(post)
return render(request, 'blog/blogpost.html')
Models.py:
from django.db import models
class Blogpost(models.Model):
post_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
head0 = models.CharField(max_length=500, default="")
chead0 = models.CharField(max_length=10000, default="")
head1 = models.CharField(max_length=500, default="")
chead1 = models.CharField(max_length=10000, default="")
head2 = models.CharField(max_length=500, default="")
chead2 = models.CharField(max_length=10000, default="")
pub_date = models.DateField()
thumbnail = models.ImageField(upload_to='blog/images', default="")
def __str__(self):
return self.title
Error
Error in cmd
Not Found: /blog/blogpost
[21/Jun/2022 12:29:33] "GET /blog/blogpost HTTP/1.1" 404 2678
The current error means Django doesn't find anything with the route blog/blogpost, it is because you have also defined an id to be pass in route, so kindly try http....blog/blogpost/1/ any id you can give.
Also, id is generally used to get a single object, and you are doing filtering on it. I think you should use get_object_or_404 if you want to retrieve single object.
As #lvanStarostin stated in the above comment that URL patterns should also have unique names. You should change one of the names.
Note: Models are classes of python so they must be written in PascalCase, so you may change your model name to BlogPost from Blogpost.
I'm using Django and I'm getting the error AttributeError at /admin/network/post/
'Post' object has no attribute 'user'
The strange thing is this error happens when I'm looking at the admin section, and clicking 'Posts.' I only have models for users and posts. Not sure how to fix this error because so far I've never gotten an error like this when clicking it in the admin section of the site: http://127.0.0.1:8000/admin/
I think the issue is in my model because the view for creating a post works totally fine.
models.py
class User(AbstractUser):
pass
class Post(models.Model):
text = models.TextField(max_length=500, blank=True, null=True)
username = models.ForeignKey('User', on_delete=models.CASCADE,
related_name='author',
null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add=True)
like = models.ManyToManyField(
User, blank=True, related_name="liked_user")
def __str__(self):
return self.user.username
class Follow(models.Model):
target = models.ForeignKey('User', on_delete=models.CASCADE,
related_name='followers')
follower = models.ForeignKey('User', on_delete=models.CASCADE,
related_name='targets')
views.py
def make_post(request):
if request.method == "GET":
form_for_post = {'form': PostForm()}
return render(request, "network/make_post.html", form_for_post)
else:
form = PostForm(request.POST)
if form.is_valid():
text = form.cleaned_data['text']
new_post = Post.objects.create(
text=text,
username=request.user,
)
return render(request, "network/make_post.html", {
"new_post": new_post,
})
You defined the field that refs to a User in the Post model to be username, not user, although user should be a better idea.
You thus should implement the __str__ method as:
class Post(models.Model):
# …
username = models.ForeignKey('User', on_delete=models.CASCADE, related_name='author', null=True, blank=True)
# …
def __str__(self):
return self.username.username
Note: It is normally better to make use of the settings.AUTH_USER_MODEL [Django-doc] to refer to the user model, than to use the User model [Django-doc] directly. For more information you can see the referencing the User model section of the documentation.
I am developing an app that needs users to login and create posts. The post model has an image and a caption (the user inputs) and a profile foreign key that should to automatically pick the logged in users profile.
The app however isnt autopicking the profile
Can someone spot what am doing wrong? I feel like the particular issue is in this line of code in my views
form.instance.profile = self.request.Image.profile
models
from django.db import models
from django.contrib.auth.models import User
import PIL.Image
from django.urls import reverse
# Create your models here.
class Image(models.Model):
image = models.ImageField(upload_to='images/')
caption = models.TextField()
profile = models.ForeignKey('Profile', default='1', on_delete=models.CASCADE)
likes = models.ManyToManyField(User, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
def get_absolute_url(self):
return reverse('vinsta-home')
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
photo = models.ImageField(upload_to = 'photos/',default='default.jpg')
bio = models.TextField(max_length=500, blank=True, default=f'I love vinstagram!')
def __str__(self):
return f'{self.user.username}'
views
from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import (ListView,CreateView,)
from .models import Image
def home(request):
context = {
'posts': Image.objects.all()
}
return render(request, 'vinsta/home.html', context)
class ImageListView(ListView):
model = Image
template_name = 'vinsta/home.html' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-created_on']
class ImageCreateView(LoginRequiredMixin, CreateView):
model = Image
fields = ['image', 'caption']
def form_valid(self, form):
form.instance.profile = self.request.Image.profile
return super().form_valid(form)
I think you're just about right as to which line isn't working. Instead of
form.instance.profile = self.request.Image.profile
try
form.instance.profile = Profile.objects.get(user=self.request.user)
(Don't forget to add the import for your Profile model.) I don't think Image exists as a property of request, but user does.
i tried to make search field to search by author in the admin panel but i got an error
Related Field got invalid lookup: icontains
i follow the documentation and other stackoverflow question but it doesn't work
#model.py
from django.contrib.auth import get_user_model
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(verbose_name='content')
date_published = models.DateTimeField(auto_now_add=True)
date_edited = models.DateTimeField(auto_now=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(blank=True)
def __str__(self):
return self.title
#admin.py
from django.contrib import admin
from .models import Post, Author,
class PostAdmin(admin.ModelAdmin):
list_display = ['title',
'date_published',
'date_edited',
'author', ]
search_fields = ['title',
'author__user',]
admin.site.register(Post, PostAdmin)
admin.site.register(Author)
it works when i changed the search_field[1] to author__id, but since it only accept id, it can't get the username. any idea how to solve it? should i make custom user model?
Question: How to show data in Django admin page which user send by forms\fields from webpage?!
P.S. I am just beginner in Django so I think my question has easy solution but right now I dont know how to make it. Don`t judge me harshly please. I will be happy for any example or article about it. =)
forms.py
class TicketForms(forms.Form):
name = forms.CharField(max_length=120, required=True)
email = forms.EmailField(required=False)
department = forms.CharField(max_length=120, required=True)
room = forms.CharField(max_length=100, required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
models.py
from django.db import models
class Ticket(models.Model):
name = models.TextField(null=True, blank=True)
email = models.TextField(null=True, blank=True)
department = models.TextField(null=True, blank=True)
room = models.TextField(null=True, blank=True) # TextField cause room can be 408A as example
comment = models.TextField(null=True, blank=True)
def __str__(self): # __unicode__ on Python 2.7
return self.name
admin.py
from django.contrib import admin
from .models import Ticket
# Register your models here.
class Admin(admin.ModelAdmin):
class Meta:
model = Ticket
admin.site.register(Ticket, Admin)
Since you have empty admin page, this means you did not registered your models yet in the admin interface. Simply go to app each in the same directory as models.py you should find admin.py and if not just create it and add the following:
1.
admin.py
from django.contrib import admin
from ticket.models import Ticket
admin.site.register(Ticket)
2.then add your app to settings.py:
INSTALLED_APPS = (
...
'tickets',
)
3.apply migrations
python manage.py makemigrations
python manage.py migrate
Now that you model is ready in views.py:
def home(request):
form = TicketForms(request.POST)
# validate your form
if form.is_valid():
Ticket.objects.create(**form.cleaned_data)
# return success url
else:
context = {'form': form}
render(request, 'ticket.html', context)
Check you admin again and you will find the saved data displayed.
And since you are new to Django I will recommend you to go through this official django tutoriel with 7 parts.