I am looking for a way to implement the "add new model_name" functionality from Django admin to normal form in templates, i.e; outside of Django admin, how could I use the same functionality.
How could I achieve it?
The first Step is to create Business Module inside models.py
class Business(models.Model):
name = models.CharField(max_length=200, db_index=True)
slug = models.SlugField(max_length=200, db_index=True, unique=True)
class Meta:
ordering = ('name',)
verbose_name = 'business'
verbose_name_plural = 'business'
def __str__(self):
return self.name
Then use python manage.py migrate to migrate module inside your database.
Now open admin.py file and register this Module,
from .models import Business
# Register your models here.
class BusinessAdmin(admin.ModelAdmin):
list_display = ['name', 'slug']
prepopulated_fields = {'slug': ('name',)}
admin.site.register(Business,BusinessAdmin)
Now check your Django admin panel. It will show you New Business Module there with Add, remove feature using Form.
I hope this will helpful for you.
Related
I'm new to Django, and I'm trying to create a "game" model with two attributes:
A many-to-one field where multiple instances of the game model are associated with an instance of a custom user model.
A many-to-many field where instances of the game model are connected with multiple instances of words, and instances of the word model are connected with multiple instances of the game model
Top of my models.py model:
from django.db import models
from users.models import CustomUser
from django.contrib.postgres.fields import ArrayField
Game model:
class SortingGame(models.Model):
user_current_player = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
field_words = models.ManyToManyField(Word, related_name="field_sorting_games")
Word model:
class Word(models.Model):
str_word = models.CharField(max_length=50,null=True)
int_grade_level = models.IntegerField()
arrint_phonemes = ArrayField(models.CharField(max_length=50),null=True)
arrstr_graphemes = ArrayField(models.CharField(max_length=50),null=True)
int_num_syllables = models.IntegerField()
arrstr_syllables = ArrayField(models.CharField(max_length=50),null=True)
User model:
class CustomUser(AbstractBaseUser):
# must have the following fields for django
email = models.EmailField(verbose_name="email",max_length = 100,unique=True)
username = models.CharField(max_length = 30, unique = True)
date_joined = models.DateTimeField(verbose_name = "date_joined",auto_now_add=True)
last_login = models.DateTimeField(verbose_name = "last_login",auto_now = True)
is_admin = models.BooleanField(default=False)
is_superuser = models.BooleanField(default = False)
is_staff = models.BooleanField(default = False)
is_active = models.BooleanField(default = True)
first_name = models.CharField(max_length=15, blank=True)
last_name = models.CharField(max_length=30, blank=True)
spelling_level = models.IntegerField(default=1, unique=False)
time_played = models.IntegerField(default=0, unique=False)
percent_correct = models.IntegerField(default=0, unique=False)
admin.py:
from django.contrib import admin
from .models import Word, SortingGame
admin.site.register(SortingGame)
When I run python3 manage.py makemigrations and python3 manage.py migrate, it doesn't complain, but when I go to the admin page of my django site it says psycopg2.errors.UndefinedColumn: column "user_current_player_id" of relation "game_sortinggame" does not exist.
This makes me think the issue is with user_current_player in SortingGame (it worked fine before I added that attribute), but I've looked around on different forums to see what might be going wrong and I can't seem to figure it out. I tried starting from scratch with a new database, and it's still throwing the same exception. Any ideas would be appreciated—thanks!
Nathan!
First thing would be make sure that you have the app where CustomUser model is created in your settings.py file, at INSTALLED_APPS.
If so, please have a look at this folder (app) where you have CustomUser defined to verify if there is in deed a migrations folder there.
I suspect that Django in not aware of this app (not under INSTALLED_APPS) and therefore did not migrated it. So, your database is not finding the User Model connection.
That said, I would suggested you to keep your account model as defined by Django User and create another model with a direct relationship to it to deal with profile/game fields such as spelling level, percentage_correct and so on.
This would keep your Model "concerns" more organized later on.
if you did make a migrations before try to use (python manage.py makemigrations -appname)
Also after That you need to Add the module in your admin.py
from django.contrib import admin
from .models import *
admin.site.register(SortingGame)
... all other modules
I have a model called listings and I want staff users to only be able to view, edit, delete listings in the admin panel that they created. Currently staff users can view edit and delete all of the listings
here is my listings/admin.py
from django.contrib import admin
from .models import Listing
class ListingAdmin(admin.ModelAdmin):
list_display =('id','Full_Name','Is_Published','Town_Or_City','District','Region','List_Date')
list_display_links = ('id','Full_Name')
list_editable = ('Is_Published',)
search_fields = ('Full_Name','Town_Or_City','District','Region',)
admin.site.register(Listing, ListingAdmin)
here is my listings/models.py
from django.db import models
from datetime import datetime
from FuneralHomes.models import FuneralHome
class Listing(models.Model):
index = models.ForeignKey(index, on_delete=models.DO_NOTHING,blank=True)
Full_Name = models.CharField(max_length=200)
First_Name = models.CharField(max_length=200)
Last_Name = models.CharField(max_length=200)
Nee = models.CharField(max_length=200, blank=True)
Town_Or_City = models.CharField(max_length=200)
District = models.CharField(max_length=200, blank=True)
Region = models.CharField(max_length=200)
List_Date = models.DateField(max_length=200)
Photo = models.ImageField(upload_to='photos/%Y/%m/%d', blank=True)
Is_Published = models.BooleanField(default=True)
List_Date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.Full_Name
The admin panel really isn't the place for things like this (as explained in the first paragraph of the Django documentation).
A quick a dirty way of accomplishing what you're trying to do is probably overriding the delete method for this model to check if the user created it. For only listing the user's posts you could utilize the Manager class. Finally, to handle editing, you would have to override the save method to see if it already exists and if the user created it.
you can override get_queryset function and just filter listings related to that user , in this case user can only see his listings .
class ListingAdmin(admin.ModelAdmin):
def get_queryset (self, request):
return Listing.objects.filter(listing_user = request.user)
I need to add job offers section to my company site (as a intro to django for me). The problem is that when i inherit my model from mezzanine's Page model it adds to admins create form all bunch of field which i dont need (like publish dates, draft field, comment field etc). I want to make create/edit job offers form as simple as possible.
I tried to inherit it from basic models.Model but it throws an error ...
Unknown column 'project_joboffer.id' in 'field list'"
I tried to customize Admin Form but im still getting error above.
models.py
class JobOffer(models.Model):
title = models.CharField(max_length=255, null=False, blank=False)
place = models.CharField(max_length=255, null=True, blank=True)
date = models.DateTimeField(auto_now_add=True)
content = models.TextField(blank=False,null=False)
published = models.BooleanField(default=True)
deleted = models.NullBooleanField()
forms.py
from django import forms
from ckeditor.widgets import CKEditorWidget
from models import JobOffer
class JobOfferForm(forms.ModelForm):
title = forms.CharField(max_length=255, required=True)
place = forms.CharField(max_length=255, required=False)
content = forms.CharField(required=True , widget=CKEditorWidget())
published = forms.BooleanField(initial=True)
deleted = forms.NullBooleanField()
# class Meta:
# model = JobOffer
admin.py
class JobOfferAdmin(admin.ModelAdmin):
form = JobOfferForm
admin.site.register(JobOffer, JobOfferAdmin)
OK, i fixed it. Migrations creating and deleting wasnt enough. I dont know why but this time i had to also delete entry in django_migrations table.
How can i extend django sites framework?
I need to add more fields, like logo file, subtitle, etc.
Or any other solution for this kind of thing?
just make OneToOne Relation with Site Model
from django.contrib.sites.models import Site
class CustomSite(models.Model):
class Meta:
verbose_name = "Custom Domain"
verbose_name_plural = "Custom Domains"
site = models.OneToOneField(Site, null=True, related_name='customsite')
subtitle = models.CharField(max_length=100)
#...
#...
def __unicode__(self):
return 'Customsite of {0}'.format(self.site.domain)
i have two models
class Reporter(models.Model):
full_name = models.CharField(max_length=70)
# On Python 3: def __str__(self):
def __unicode__(self):
return self.full_name
class Article(models.Model):
pub_date = models.DateField()
headline = models.CharField(max_length=200)
content = models.TextField()
reporter = models.ForeignKey(Reporter)
now in the admin site i want to register the reporter's model and then when it is clicked the Article model objects can be added from within that reporter's model .. is it possible ?? if yes how to accomplish this ??
You need inline model admin. In your admin.py, add the following:
from django.contrib import admin
from .models import Article, Reporter
class ArticleInline(admin.TabularInline):
model = Article
class ReporterAdmin(admin.ModelAdmin):
inlines = [
ArticleInline,
]
admin.site.register(Reporter, ReporterAdmin)