I have 2 Models in my django models.py.
I need to get data from model2 to model1, but I don't need to store it anywhere in the model1 fields. I found #property of django and implemented that. My issue was that I need to get who the user is using request.user, which is not possible in models.py
So how can I access user in django models? Is there any other packages? or is there any inbuilt django way which I haven't thought about?
I searched and got a package called django-currentuser , unfortunately i'm using Django 4 which doesn't have a support.
I didn't get exactly what's your problem.
if you want to get the current user in django,this should be handled in your views like:
def View(request):
user = request.user
and if the other model that you got data from have any field connected to User like:
user = models.Foreignkey(User,...)
you can easily achive the user...
please describe more...
This is my models.py file
from django.db import models
# Create your models here.
class Item(models.Model):
name=models.CharField(max_length=250)
description = model.TextField()
class Meta:
oredering['name']
def __unicode__(self):
return self.name
#permalink
def get_absolute_url:
retun ('item_detail',None,{'object_id':self_id})
class Photo(models.Model):
item = models.ForiegnKey(Item)
title=models.ChaField(max_length=250)
image=models.IMageField(upload_to='photos')
caption=models.TextField(blank=True)
class Meta:
ordering=['title']
def __unicode__(self):
return self.title
#permalink
def get_absolute_url(self):
retun ('photo_detail',None,{'object_id':self_id})
And this is my admin.py :
from django.contrib import admin
from models import Item
from models import Photo
# Register your models here.
class PhotoInline(admin.StackedInline):
model = Photo
class ItemAdmin(admin.ModelAdmin):
inlines = [PhotoInline]
admin.site.register(Item, ItemAdmin)
admin.site.register(Photo)
But, I can't understand what is StackedInline and TabularInline, I referred to Django documentation but still couldn't understand what exactly it was.
Also, I can't see those models in my admin panel when I started the server, I don't understand why my models aren't registered on my admin page.
I see two different questions:
I cant understand what is stacked inline and tabular inline
Basically, both allow you to edit models on the same page as a parent model. In other words, it is sometimes preferable for a user to have the possibility to edit a certain model while editing another one instead of having to manually add another instance somewhere else in your interface. In your particular case, you can use it to facilitate user experience by allowing the user to add photos linked to a parent item simultaneously whitout having to constantly change between your admin forms.
Now, the difference between the two is really simple to understand: Layout. Indeed, both works exactly the same behind the scenes, the only difference is the template used for rendering. It can be seen here in the source code. So, picking one for your project is only a matter of preference regarding the interface layout
I cant see those models in my admin panel
This can be a lot of things, but often it's because you forgot to run your migrations with makemigrations and migrate. If you did, another thing that a lot of users forget is to install their app. So, in
Setting.py
INSTALLED_APPS = ['Myproject.apps.Myapp']
The TabularInline displays data in table
But StackedInline displays in row
Hello everyone how is it going?
I've just started using Django recently, and I've started getting my head around it; I need to build a website about cars, with two major APPS:
CarsCatalogue;
News Section;
I find the fact that I can manage the news from the admin panel extremely useful. I have created the typical model:
class Post(models.Model):
title = models.CharField(max_length = 140)
date = models.DateTimeField()
body = models.TextField()
def __str__(self):
return self.title
With the urls.py as follows
url(r'^(?P<pk>\d+)$', DetailView.as_view(
model = Post,
template_name="news/post.html"))
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="news/news.html")),
This is great! I can manage the News app Extremely easyly from the admin panel. Now I have a page for each news: news/1; news/2 etc etc;
But when i go down to the CarsCatalogue, and I would really need to simplify my life because I have plenty of cars with a personal page each to add, I am instead finding myself needing to modify the urls.py for each car I need to add, and it seems I have to modify the views.py for each car -I am using render- am I right?
I mean, does it make sense to have a Views.py with one hundred different functions calling one hundred pages?
And then if I want to create a list with all the urls of the CarCatalogue, having to write every link one by one?
Is this the way to use Django in this case?
I would create another "news-style" APP for CarsCatalogue, that would be so much more easy for me to manage through the Admin Panel, but I need each url to show the car name, like: CarsCatalogue/Seat-Ibiza and not like CarsCatalogue/1.
Maybe I can do something like the news APP, but changing the way urls are generated and shown?
I am asking you all of this after I read the documentation and several Google topics and other resources;
I hope you guys will be able to clear the fog around my head;
With all the Respect such a community deserves,
Sincerely,
-oKi
EDIT n*1
It's been 3 hours of reading, trying, modifying, erasing, trying again.
I read a lot of stuff, but at the same time I got pheraps even more confused, because I found so many things while looking for how to "slug"ify the urls (that is indeed what I was looking for [now I can indeed use the admin panel to do what I wanted!] thanks) that I ended up mixing a lot of stuff. So, using the NEWS application, what I have done so far:
python3.5 manage.py flush, makemigrations, migrate, createsuperuser
I modified the news/models.py, so that it now looks like this:
from django.db import models
from django.template.defaultfilters import slugify
class Post(models.Model):
title = models.CharField(max_length = 140)
date = models.DateTimeField()
body = models.TextField()
slug = models.SlugField(title, max_length=100, unique=True)
def __str__(self):
return self.title
def slug(self):
return slugify(self.title)
I modified the news/admin.py, so that it now looks like this:
from django.contrib import admin
from news.models import Post
admin.site.register(Post)
class NewsAdmin(admin.ModelAdmin):
prepopulated_fields = {"slug": (Post.slug)} <!-- that seems makes sense looking at the Model - I also tryed {"slug": (title,)}, {"slug": (Post.title)}-->
I modified the news/urls.py, so that it now looks like this:
from django.conf.urls import url
from django.views.generic import ListView, DetailView
from news.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all().order_by("-date")[:25],
template_name="news/news.html")),
url(r'^(?P<slug>[\w-]+)$', DetailView.as_view(
model = Post,
template_name="news/post.html")),
]
then I give:
python3.5 manage.py runserver
and it runs with no problem.
So I go to /admin, I create a new post, it creates it...
But then what happens?
It still uses the old "paradigm" to generate the url, including the old keys(id's) it was using before I erased the client... so... what I expected to be something like mysite/news/new-human-level-urld-news
turns out to be mysite/news/11.
LOL :D and, luckily, the browser gives me also an error...
"FieldError at /news/11
Cannot resolve keyword 'slug' into field. Choices are: body, date, id, title"
at the moment I can't find an answer, I find so much stuff that I just don't know how to mix things up. I will keep searching. Help is appreciated! Thanks for now!!! :D
According to my understanding to your problem, what you need is not to create a view function for every car you have.
Indeed, you need to create 1 template (html page) that describes your CarsCatalogue, where all the CarsCatalogues have the same structure with different information. Then the user chooses one CarsCatalogue, let's say from a dropdown control and then you load the data from your database and show your results in the template.
In order to achieve this, have a look on the following topics:
Django forms. And in order to get your data from the database, you need the the id for example to be passed in the url, you can see this answer how to pass an id in django url or from the official website URL Dispatcher.
In few words, django is a simple way to do your website and definitely no need to rewrite your code several times.
NO THERE IS NO NEED TO CREATE MULTIPLE URLS.
From what I understood, you want a catalogue for each car.
Just create a view from where you display the names of all your cars.
Then when you click on a car, make a get request to another view function in the get request pass your selected car details. Now comes the use on Django Templates. Create a Django template for your catalogue, pass the car specific data to it.
You need to read about Django Templates , I think Django templates is something that will solve your problem.
I think the thing you're missing is that the parameter in the URL can be anything, not just a numeric URL. If it's a string, we call that a slug, and the Django admin will automatically create a slug from the fields in your model if you set the prepopulated_fields option.
Then, you can use that slug in the URL:
url(r'^(?P<slug>[\w-]+)$', DetailView.as_view(
model = Car,
template_name="news/car.html"))
and Django will use that field instead of the ID to find the right content to display.
I found a way to fix my problem.
Even though I started off by asking about the CARS Catalogue, I will explain what I did using the NEWS APP instead, as the logic is the same and as that is the APP I have modified in the first EDIT of my post.
Inside the Templates, have a "news.html" page to render the list of all the Post, and a "post.html" to render every single Post.
The following is part of the procedure on how to set an APP that you can manage directly from the ADMIN PANEL, and that uses the SLUG field as URL.
models.py:
from django.db import models
class Post(models.Model):
title = models.CharField(max_length = 140)
body = models.TextField()
slug = models.SlugField(unique=True)
def __str__(self):
return self.title
admin.py:
from django.contrib import admin
from news.models import Post
class PostAdmin(admin.ModelAdmin):
model = Post
prepopulated_fields = {'slug': ('title',)}
admin.site.register(Post, PostAdmin)
urls.py:
from django.conf.urls import url
from django.views.generic import ListView, DetailView
from news.models import Post
urlpatterns = [
url(r'^$', ListView.as_view(
queryset=Post.objects.all(),
template_name="news/news.html")),
url(r'^(?P<slug>[\w-]+)$', DetailView.as_view(
queryset=Post.objects.all(),
model = Post,
template_name="news/post.html")),
]
I hope that can be useful to somebody.
Jeez you gotta study hard to use this Framework :D
Thanks everybody for the support, c ya :)
I tried to apply mptt in my django program on a existing model using the method provided on the main site of mptt, which is as follow:
import mptt
from mptt.fields import TreeForeignKey
from django.contrib.auth.models import Group
# add a parent foreign key
TreeForeignKey(Group, blank=True, null=True, db_index=True).contribute_to_class(Group,'self')
mptt.register(Group, order_insertion_by=['name'])
However, when I open my group list in the admin-site, it says that the group model doesn't have such column named parent_id, I wonder how I can fix it.
BTW the code have been written in models.py,is it possible that I should have written it in admin.py?
reference: Registration of existing models
Edit:
sorry about the comment...migrations does solve the problem ><
However it leads to another question...can I only create a group by code to create a new tree structure, or it's possible for me to do that somewhere in my admin site?
Thanks for the answering and attention:)
I have a model created in Django 1.5 as below:
class Number(models.Model):
phone_number = models.CharField("Phone Number", max_length=10, unique=True)
I set up Django admin as below:
from django.contrib import admin
from demo.models import Message, Number, Relationship, SmsLog
class NumberAdmin(admin.ModelAdmin):
search_fields = ['phone_number']
admin.site.register(Number, NumberAdmin)
I believe Django add "date_created" column to the database automatically (because I know it sorts the data entries by creation time in admin console). Is there a way to view those time/dates in admin console? The closest I have go to is Django tutorial and StackOverflow ,but I do not want to create another column on my own (pub_date in Django official tutorial's example) and add it if possible. Is there a way to do it and if so, could someone show me how to? Thank you!
Django does not automatically add a date_created column. If you want to track the creation date, you have to declare it in your model.
You may be getting the illusion that it does because if you do not specify a sort order in the model or in the admin class for the model, it will default to sorting by primary key, which will increase according to the order the model instances were created.