How to pass value as string in ForeignKey and not integer? - django

IMPORT PHOTO
I tried to import my model in admin to csv file and the output of the foreignkeys are integers(see Department and Status fields in photo above). How can i convert that into string?

You can check how to add relationship fields the documentation. It suggests adding two classes: a resource class to define which fields are exported and an admin class that connects the resource class to the admin interface. In your case admin.py may look like
from django.contrib import admin
from models import *
from import_export.admin import ImportExportModelAdmin
from import_export import resources
class HrmResource(resources.ModelResource):
class Meta:
model = hrm
fields = ('name', 'place', 'department__nm_dept')
class HrmAdmin(ImportExportModelAdmin):
resource_class = HrmResource
admin.site.register(r_dept)
admin.site.register(hrm, HrmAdmin)
and models.py like
from django.db import models
class r_dept(models.Model):
nm_dept = models.CharField(max_length=200)
def __str__(self):
return self.nm_dept
class hrm(models.Model):
name = models.CharField(max_length=200)
place = models.CharField(max_length=200)
department = models.ForeignKey('r_dept')
def __str__(self):
return self.name

Related

How to ordering category items a to z in django admin panel?

I have a business directory and when i add new company, categories listing mixed style. How can i order categories a to z.
I added my model these meta ordering but didn't worked.
class Category(models.Model):
name = models.CharField(max_length=100)
class Meta:
ordering = ['name']
You can write a class in your admin.py file, like the following:
from django.contrib import admin
from .models import Category
class CategoryAdmin(admin.ModelAdmin):
ordering = ['name']
admin.site.register(Category,CategoryAdmin)

how to create tag field in django form like youtube have

i want to create a tag field like youtube give tage field while uploading a vedio this is what i tried in in my blog form
my models.py
from django.db import models
from django.contrib.auth.models import User
from django.utils import timezone
# Create your models here.
class Blog(models.Model):
author = models.OneToOneField(User, on_delete=models.CASCADE,)
title = models.CharField(max_length=200,blank=False,)
thumbnail = models.ImageField(upload_to='blogs_thumbnail',default='blogdefa.png')
tags = models.CharField(max_length=500, blank=False, default='Blog')
data = models.TextField(blank=False,)
published_date = models.DateTimeField(default=timezone.now,editable=False)
update_at = models.DateTimeField(auto_now=True,editable=False)
def __str__(self):
return self.title
any idea how to do it i don,t know how to do it
my forms.py
from django import forms
from django.forms import ModelForm, Textarea
from django.contrib.auth.models import User
from .models import Blog, comment, report
forms here
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = '__all__'
widgets = {'data': Textarea(attrs={'cols': 80, 'rows': 20, 'placeholder':'Write Here'}),
'title':forms.TextInput(attrs={'placeholder':'Your Blog Title Here'}),
'tags': forms.TextInput(attrs={'placeholder':'Please enter you content related tags'}),
}
exclude = ['author','published_date','update_at']
all i want is user can create his own tag for blogs like in youtube and not like stackoverflow where you have use to choose you tag
please help
currently it look like this
which is not cool
First thing is that tags work. So to get them working you should relate it to your post.
So you should create a Tag model and use a ManytoManyRelated field to relate tags because you need to get to the post/result at the end using tags.
from django.db import models
from django_extensions.db.fields import AutoSlugField
from django.db.models import CharField, TextField, DateField, EmailField, ManyToManyField
class Tag(models.Model):
name = CharField(max_length=31, unique=True, default="tag-django")
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
def __str__(self):
return self.name
class YourPost(models.Model):
name = CharField(max_length=31, db_index=True)
slug = AutoSlugField(max_length=31, unique=True, populate_from=["name"])
description = TextField()
date_founded = DateField(auto_now_add=True)
contact = EmailField()
tags = ManyToManyField(Tag, related_name="tags")
class Meta:
get_latest_by = ["date_founded"]
def __str__(self):
return self.name
Go on from here.
Create serializers, Viewsets. Relate your tags to your post.

Django-Rest-Framework error: Field name 'product_name' is not valid for model 'Store'

In my Django Rest Framework API app, I am trying to add a field "product_name" in Product model, "product_name" field is not related to Store model as shown below:
Models.py
from django.db import models
# Create your models here.
class Store(models.Model):
company_name=models.CharField(max_length=50)
company_gst_no=models.CharField(max_length=200)
class Product(models.Model):
company_name=models.ForeignKey(Store, on_delete=models.CASCADE)
product_name=models.CharField(max_length=200, null=True)
class Purchase(models.Model):
company_name=models.ForeignKey(Store, on_delete=models.CASCADE)
p_n=models.ForeignKey(Product, on_delete=models.CASCADE)
purchase_rate=models.IntegerField(null=False)
purchase_quantity=models.IntegerField(null=False)
serializers.py
# api/serializers.py
from rest_framework import serializers
from .models import *
class StoreSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Store
fields = ['url','id','company_name', 'company_gst_no']
class ProductSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Product
fields = ['url','id', 'product_name']
class PurchaseSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Purchase
fields = ['url','id','company_name']
views.py
from django.shortcuts import render
from rest_framework import generics, viewsets
from .models import *
from .serializers import *
# Create your views here.
class StoreList(viewsets.ModelViewSet):
queryset = Store.objects.all()
serializer_class = StoreSerializer
class Product(viewsets.ModelViewSet):
queryset = Product.objects.all()
serializer_class = ProductSerializer
class Purchase(viewsets.ModelViewSet):
queryset = Purchase.objects.all()
serializer_class = PurchaseSerializer
Error is "ImproperlyConfigured at /product/" "Field name product_name is not valid for model Store."
Have you tried using another name? For example:
name=models.CharField(max_length=200, null=True)
If you receive same error, is because is not a problem of the field.
In that case... Did you apply migrations after adding this field?
python manage.py makemigrations
python manage.py migrate

How to make a field read-only inside a CreateView

I am a Django beginner and I am trying to make read-only a 'price' field for an order. I think, based on what I have understood, this cannot be done inside the model itself, but rather inside a form.
Since I am using a CreateView generic view, I thought this could have been done by setting the attribute disabled equal to True, as said here.
so what I have done is, in views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .models import Order
from django import forms
# Create your views here.
class CreateOrderView(CreateView):
model = Order
template_name = 'home.html'
meal_price = forms.DecimalField(disabled=True)
fields = [
'meal_name',
'meal_price',
'restaurant',
'customer',
]
But this doesn't work.
Here is my models.py
from django.db import models
from restaurant.models import Restaurant
from account.models import Customer
# Create your models here.
class Order(models.Model):
meal_name = models.CharField(max_length=255)
meal_price = models.DecimalField(max_digits=5, decimal_places=2)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, default=None)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, default=None)
Can anybody give me a hint?
Please consider that I am still learning so I would prefer coded answers to descriptive ones.
Thank you in advance
Ok, thanks to dirkgroten, I have worked out the answer.
Basically what is needed (in my case) is:
an Order model in models.py
from django.db import models
from restaurant.models import Restaurant
from account.models import Customer
# Create your models here.
class Order(models.Model):
meal_name = models.CharField(max_length=255)
meal_price = models.DecimalField(max_digits=5, decimal_places=2)
restaurant = models.ForeignKey(Restaurant, on_delete=models.CASCADE, default=None)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, default=None)
an OrderForm(ModelForm) in forms.py that modifies the price field setting the disabled attribute to true
from django.forms import ModelForm
from .models import Order
from django import forms
class OrderForm(ModelForm):
meal_price = forms.DecimalField(max_digits=5, decimal_places=2, disabled=True)
class Meta:
model = Order
fields = [
'meal_name',
'meal_price',
'restaurant',
'customer',
]
an OrderView(CreateView) in views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .forms import OrderForm
# Create your views here.
class OrderView(CreateView):
form_class = OrderForm
template_name = 'home.html'
I have no experience with Django's CreateView but from what I read it works similar to a separate form. You could try something like this:
class CreateOrderView(CreateView):
model = Order
template_name = 'home.html'
fields = [
'meal_name',
'meal_price',
'restaurant',
'customer',
]
def __init__(self, *args, **kwargs):
super(CreateOrderView, self).__init__(*args, **kwargs)
self.fields['meal_price'].widget.attrs['disabled'] = True
From my experience, the disabled attribute will be good for security reasons as far as protecting against the user editing the HTML and changing the value. However you won't be able to access this value when passed into a clean method. If you need to perform actions on the value you should change 'disabled' to 'readonly', but you won't have the same data protection that disabled offers.

django foreign key

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.