If I have two apps, with separate urls.py files, how can I reference the view from on app in another so that I can include references with a HyperLinkedField?
Let's define two models in separate apps
class Document(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
text = models.TextField()
class CustomUser(models.Model):
name = models.TextField()
Now the Serializers
class DocumentSerializer(serializers.ModelSerializer):
user_link = HyperlinkedRelatedField(view_name="user-detail")
class Meta:
model = Document
fields = ('user_link', 'text')
and now for the relevant urls.py
urlpatterns = patterns('',
url(r'(?P<pk>[0-9]+)/$',
views.UserDetail.as_view()
name='user-detail'
),
)
Related
I am trying to use django autocomplete light to set up Autocompletion for GenericForeignKey
However I am getting this error when I try to view the form:
I have a simple a setup. But because the urls are in an app's namespace, it can't find them.
models.py
class Prereq(IsAPrereqMixin, models.Model):
name = models.CharField(max_length=256, null=True, blank=True)
prereq_content_type = models.ForeignKey(ContentType, related_name='prereq_item',
verbose_name="Type of Prerequisite",
on_delete=models.CASCADE)
prereq_object_id = models.PositiveIntegerField(verbose_name="Prerequisite")
prereq_object = GenericForeignKey("prereq_content_type", "prereq_object_id")
# lots more fields ignored for now
forms.py
from dal import autocomplete
from prerequisites.models import Prereq
class PrereqForm(autocomplete.FutureModelForm):
prereq_object = autocomplete.Select2GenericForeignKeyModelField(
model_choice=[(Prereq, "Prereq"), ]
)
class Meta:
model = Prereq
fields = ['name']
urls.py
from django.urls import path
from prerequisites import views
from prerequisites.forms import PrereqForm
app_name = 'prerequisites'
urlpatterns = [
path('edit/<int:pk>/', views.PrereqUpdateView.as_view(), name='prereq_edit'),
]
# https://django-autocomplete-light.readthedocs.io/en/master/gfk.html#register-the-view-for-the-form
urlpatterns.extend(PrereqForm.as_urls())
I need to make REST part which on url would look like this:
GET POST api/groups/{group_id}/users/
PUT PATCH DELETE api/groups/{group_id}/users/{user_id}
So I could see users which are related to the pointed group. Is there any way for such case? Thanks :)
Code example:
.models
class User(models.Model):
nickname = models.CharField(max_length=30)
email = models.CharField(max_length=60)
class Group(models.Model):
name = models.CharField(max_length=60)
user = models.ForeignKey(User, on_delete=models.CASCADE)
I have simplest serializers and view sets look like:
.serializers
class UserSerializer(ModelSerializer):
class Meta:
model = models.User
fields = '__all__'
class GroupSerializer(ModelSerializer):
class Meta:
model = models.Group
fields = '__all__'
.views
class UserViewSet(viewsets.ModelViewSet):
queryset = models.User.objects.all()
serializer_class = serializers.UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
queryset = models.Group.objects.all()
serializer_class = serializers.GroupSerializer
Have a look at drf-nested-routers. It's a really nice library that helps define routes exactly like this.
A quick example is for URLs like this:
/domain/ <- Domains list
/domain/{pk}/ <- One domain, from {pk}
/domain/{domain_pk}/nameservers/ <- Nameservers of domain from {domain_pk}
/domain/{domain_pk}/nameservers/{pk} <- Specific nameserver from {pk}, of domain from {domain_pk}
The usage will be:
# urls.py
router = routers.SimpleRouter()
router.register(r'domains', DomainViewSet)
domains_router = routers.NestedSimpleRouter(router, r'domains', lookup='domain')
domains_router.register(r'nameservers', NameserverViewSet, basename='domain-nameservers')
urlpatterns = patterns('',
url(r'^', include(router.urls)),
url(r'^', include(domains_router.urls)),
)
# views.py
class NameserverViewSet(viewsets.ModelViewSet):
def get_queryset(self):
return Nameserver.objects.filter(domain=self.kwargs['domain_pk'])
I have a model with ManyToMany relationship.
class File(models.Model):
name = models.CharField(max_length=64)
def __str__(self):
return self.name
class Folder(models.Model):
name = models.CharField(max_length=64)
files = models.ManyToManyField(File, related_name='folders', default=None)
def __str__(self):
return self.name
Serializers:
class FileSerializer(serializers.ModelSerializer):
class Meta:
model = models.File
fields = '__all__'
class FolderSerializer(serializers.ModelSerializer):
files = FileSerializer(many=True, read_only=True)
file = serializers.PrimaryKeyRelatedField(queryset=models.File.objects.all(),
write_only=True, label='File Name')
class Meta:
model = models.Folder
fields = ('id', 'name', 'files', 'file')
I am able to add a file object to the folder. I am able to update the name of the folder too. But how do I remove a file object from the folder?
If you are accessing from files
file = File.objects.get(query)
Then you can do
file.folders.remove(folder_object)
Edit:
Your app's urls file:
urls.py:
from django.conf.urls import include, url
from .views import folder
urlpatterns = [
url(r'remove-folder/', folder, name='remove_folder'),
]
Your apps views.py:
def folder(request):
file = File.objects.get(query)
file.folders.remove(folder_object)
# return appropriate data
New to django, and loving it so far. I have a django admin, schema design question. I have a app that has a customer, product and order table. The customer has an order sheet of products, pre-built by admin, and saved in the CustomerProduct table. When the customer logs in they can only view their order sheet, update quantities, and that's it. They won't have access to products table or other customers order sheets. Three parts where im stuck right now,
The order table should have a many-to-many relationship with the customer_products table.
Order history needs to be saved in a separate table somehow, so if a user's order sheets changes, we still have record of their past orders. I need to construct a view for a user that will display just their order sheet. /admin/onlineordering/ordersheet.
How can I set this url up and limit access to a authenticated user. User A can only see User A's CustomerProduct (Order Sheet)
Below is the apps models.py and the admin.py
onlineordering/models.py
from django.conf import settings
from django.db import models
from datetime import datetime
class Customer(models.Model):
customer = models.ForeignKey(settings.AUTH_USER_MODEL, limit_choices_to={'groups__name': "customers"})
customer_product = models.ManyToManyField('Product', through='CustomerProduct')
company_name = models.CharField(max_length=255)
address1 = models.CharField(max_length=255)
address2 = models.CharField(max_length=255)
city = models.CharField(max_length=255)
state = models.CharField(max_length=255)
zip_code = models.CharField(max_length=255)
def __unicode__(self):
return self.company_name
class CustomerProduct(models.Model):
customer = models.ForeignKey('Customer')
product = models.ForeignKey('Product')
class Product(models.Model):
item = models.CharField(max_length=255)
description = models.CharField(max_length=255)
def __unicode__(self):
return self.description
class Order(models.Model):
customer_product_order = models.ManyToManyField('CustomerProduct', through='CustomerProductOrder')
purchase_order_number = models.CharField(max_length=10)
person_placing_order = models.CharField(max_length=255)
requested_delivery_date = models.DateField(blank=True, null=True)
class CustomerProductOrder(models.Model):
order = models.ForeignKey('Order')
customer_product = models.ForeignKey('CustomerProduct')
quantity = models.IntegerField(default=0)
onlineordering/admin.py
from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from .models import Order,Customer,Product
UserAdmin.add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('username', 'password1', 'password2', 'first_name', 'last_name', 'groups')}
),
)
class CustomerProductInline(admin.StackedInline):
model = Customer.customer_product.through
extra = 0
class ProductAdmin(admin.ModelAdmin):
inlines = [
CustomerProductInline,
]
class CustomerAdmin(admin.ModelAdmin):
inlines = [
CustomerProductInline,
]
exclude = ('customer_product',)
admin.site.register(Order)
admin.site.register(Customer,CustomerAdmin)
admin.site.register(Product)
Update
/onlineordering/views.py
from django.http import HttpResponse
def ordersheet(request):
return HttpResponse("Hello, world.")
/urls.py
from django.conf.urls import include, url
from django.contrib import admin
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^admin/onlineordering/ordersheet', include(admin.site.urls)),
]
I have the following in my models.py:
from django.db import models
class LabName(models.Model):
labsname=models.CharField(max_length=30)
def __unicode__(self):
return self.labsname
class ComponentDescription(models.Model):
lab_Title=models.ForeignKey('Labname')
component_Name = models.CharField(max_length=30)
description = models.CharField(max_length=20)
purchased_Date = models.DateField()
status = models.CharField(max_length=30)
to_Do = models.CharField(max_length=30,blank=True)
remarks = models.CharField(max_length=30)
def __unicode__(self):
return self.component
I have the following in my admin.py:
from django.contrib import admin
from Lab_inventory.models import ComponentDescription,LabName
class ComponentDescriptionAdmin(admin.ModelAdmin):
list_display= ('lab_Title','component_Name','description','purchased_Date','status','to_Do','remarks')
list_filter=('lab_Title','status','purchased_Date')
admin.site.register(LabName)
admin.site.register(ComponentDescription,ComponentDescriptionAdmin)
What I want is to display the fields under the component description to be displayed under the lab title(the fields related to each lab title by should be displayed under that lab name)
What you are doing with list_display and list_filter pertain to the list that is shown in the admin screen where the list of LabName objects are listed.
Assuming one LabName has one-to-many ComponentDescription entities, you need Django's InlineModelAdmin to display the list of ComponentDescription objects belonging to LabName within the admin page for a specific LabName entity. The code would be of the following structure:
from django.contrib import admin
from Lab_inventory.models import ComponentDescription,LabName
class ComponentDescriptionInline(admin.TabularInline):
model = ComponentDescription
class LabNameAdmin(admin.ModelAdmin):
inlines = [
ComponentDescriptionInline,
]
admin.site.register(LabName, LabNameAdmin)
where TabularInline is a subclass of the generic InlineModelAdmin.