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.
Related
I change django user model by inherited from AbstractUser, codes like the following. But I can not
modify user permissions and change the group which user belong to any more in Django admin site. When I logon to admin as super user, go to the user page. The user'permissions can not be changed. Can anyone help?
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.contrib import admin
class UserProfile(AbstractUser):
mobile = models.CharField(max_length=20, null=True, blank=True)
avatar = models.CharField(max_length=100, null=True, blank=True)
admin.site.register(UserProfile)
#settings.py add this
AUTH_USER_MODEL = 'users.UserProfile'
You should add some code in your admin.py
class ProfileAdmin(admin.ModelAdmin):
filter_horizontal = ("groups", "user_permissions")
Try it.
ref : Django-admin won't allow me to modify user permissions and groups
awkeye7 's answer is proper to me.
:)
I am writing an app in which people can submit their complaints related to some issues.
After the form is submitted, it is supposed to redirect to the page where the details of the complaint are mentioned like area of the complaint, title, description etc.
But after the form is submitted, it throws IntegrityError.
I read about it and went through some of the solutions:
Someone suggested that I delete some past migrations and run them again. I cleared the migrations, ran them again and made some posts through the admin but it is throwing the same error.
Some posts suggest that null=True, blank=True should be added but I do not understand where they should be added in my case. I also don't want to add null=True, blank=True because I don't want any field to be left blank.
Below is my models.py:
from django.db import models
from django.urls import reverse
# Create your models here.
class Complaint(models.Model):
""" Details of the complaint """
resident = models.ForeignKey('auth.User', on_delete=models.CASCADE)
AREA = [('PL', 'Plumbing'), ('EL', 'Electricity'), ('CP', 'Carpenter'), ('CO', 'Construction'), ('DS', 'Disputes'), ('OT', 'Other'),]
matter = models.CharField(max_length=2, choices=AREA)
title = models.CharField(max_length=200)
text = models.TextField()
date = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('comp_detail', args=[str(self.id)])
Below is my urls.py which I created in my 'complaint':
Note - I used class-based views in my views.py
from django.urls import path
from .views import CompListView, CompDetailView, CompCreateView
urlpatterns = [
path('comp/new/', CompCreateView.as_view(), name='comp_new'),
path('comp/<int:pk>/', CompDetailView.as_view(), name='comp_detail'),
path('', CompListView.as_view(), name='home'),
]
Some help will be appreciated.
I'm making a Blog app in Django and want to add Django-Markdown Field in Admin site for Posts model which holds data for blog posts.
What changes need I to do in the following code?
I am using Django:2.2.4 and Django-Markdown-App: 0.9.6
Here is my Post Model
ONE = 1
TWO = 2
status_choices = (
(ONE, 'draft'),
(TWO, 'published')
)
class Posts(models.Model):
title = models.CharField(max_length=255, blank=False)
content = MarkdownField()
created_date = models.DateTimeField(auto_now_add=True)
modified_date = models.DateTimeField(auto_now=True)
author = models.ForeignKey(
User,
on_delete=models.CASCADE
)
status = models.IntegerField(choices=status_choices, default=ONE)
slug = models.SlugField(max_length=255)
def __str__(self):
return self.title
class Meta:
verbose_name = "Post"
verbose_name_plural = "Posts"
Here is admin.py code
from django.contrib import admin
from .models import Posts
from django_markdown.admin import MarkdownModelAdmin
# Register your models here.
class PostsAdmin(MarkdownModelAdmin):
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Posts, PostsAdmin)
Here is settings.py
INSTALLED_APPS = [
......,
'django_markdown',
......,
]
MARKDOWN_EDITOR_SKIN = 'markitup'
Here is Project level urls.py
urlpatterns = [
.......
path('markdown/', include('django_markdown.urls')),
.......
]
I am expecting to display a markdown interface in the admin site instead of a simple text field, but the current output is a simple text field.
Looks like the jQuery script cannot be found. Can you try with this custom adminModel ?
from django_markdown.admin import MarkdownModelAdmin
class PostsAdmin(MarkdownModelAdmin):
prepopulated_fields = {'slug': ('title',)}
class Media:
js = (
'https://code.jquery.com/jquery-3.4.1.min.js', # adds jquery script
)
admin.site.register(Posts, PostsAdmin)
(Something is blocking the access to the django-admin Jquery, usually it can be used with the object django.jQuery)
I am trying to set up a basic blog with a custom auth model. I am trying to get a simple form to work but somehow I am not able to make it work. I am not sure what is causing the error. This is a fresh app and a fresh project I am working on.
I tried to reference from the docs but I am not sure what I am doing incorrect. How can i fix this error? Thanks in advance
Docs: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project
Similar questions: Cannot create form field for 'created_by' yet, because its related model 'users.User' has not been loaded yet
My Current Code
models.py
class User(AbstractUser):
pass
class Post(models.Model):
author = models.ForeignKey('settings.AUTH_USER_MODEL')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
forms.py:
from blog.models import User
class PostForm(forms.ModelForm):
image = forms.CharField(
widget=forms.FileInput(attrs={'class': 'form-control'}),required=False)
class Meta():
model = Post
fields = ('author','title', 'text','image')
widgets = {
'title': forms.TextInput(attrs={'class': 'textinputclass'}),
}
views.py
from blog.forms import PostForm, CommentForm
class CreatePostView(LoginRequiredMixin,CreateView):
...
form_class = PostForm
model = Post
def form_valid(self,form):
if self.request.POST:
post = form.save()
return HttpResponseRedirect('/')
settings.py:
AUTH_USER_MODEL = 'blog.User'
admin.py:
from .models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User,UserAdmin)
You should use settings.AUTH_USER_MODEL, not the string 'settings.AUTH_USER_MODEL':
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
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