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.
Related
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.
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
The documentation for django-import-export is a bit weak on how to configure the admin to import from a spreadsheet. Does anyone have a full example?
This is not a fully complete module. But you can understand how it should be.
resources.py file
from import_export import resources
from .models import edxUser
class edxUserResource(resources.ModelResource):
class Meta:
model = edxUser
#skip_unchanged = True
#report_skipped = True
#if you want to exclude any field from exporting
exclude = ('id','edx_anonymized_id')
fields = ('id', 'edx_id', 'edx_anonymized_id', 'edx_email', 'edx_name', 'time_created', 'created_by')
#Order of the export fields
export_order = ('edx_id', 'edx_email')
admin.py file
from import_export.admin import ImportExportModelAdmin
from django.contrib import admin
from .models import edxUser
from resources import edxUserResource
#admin.register(edxUser)
class edxUserAdmin(ImportExportModelAdmin):
resource_class = edxUserResource
models.py file
from __future__ import unicode_literals
from django.conf import settings
from django.db import models
class edxUser(models.Model):
edx_id = models.IntegerField('edX user id', blank=True, null=True)
edx_anonymized_id = models.IntegerField("edX anonymized user id", blank=True, null=True)
edx_email = models.EmailField('edx user email', max_length=75, blank=True)
edx_name = models.CharField('edx name', max_length=75, blank=True, null=True)
time_created = models.DateField('Created time', blank=True, null=True)
created_by = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, blank=True)
def __unicode__(self):
return str(self.edx_id)
Here's how to do it, assuming that the column names in the spreadsheet are Title and Field one. This example assumes that the model instances will be created afresh every import (rather than being updated via a primary key).
from django.contrib import admin
from import_export.admin import ImportMixin
from import_export import resources, fields
from .models import MyModel
class MyModelResource(resources.ModelResource):
title = fields.Field(attribute='title',
column_name='Title')
field_one = fields.Field(attribute='field_one',
column_name='Field one')
def get_instance(self, instance_loader, row):
# Returning False prevents us from looking in the
# database for rows that already exist
return False
class Meta:
model = MyModel
fields = ('title', 'field_one')
export_order = fields
class MyModelAdmin(ImportMixin, admin.ModelAdmin):
resource_class = MyModelResource
admin.site.register(MyModel, MyModelAdmin)
Hi I need really very very simple example. First my models:
#This my student models
from django.db import models
SEX_CHOICES= (
('M', 'Male'),
('F', 'Female'),
)
class Students(models.Model):
student_name = models.CharField(max_length=50)
student_sex = models.CharField(max_length=8, choices=SEX_CHOICES)
student_city = models.Charfield(max_length=50)
student_bio = models.TextField()
def __unicode__(self):
return self.student_name
O.K. Let see my ClassRooms Model.
#This my ClassRooms models
from django.db import models
from myproject.students.models import *
class ClassRooms(models.Model):
class_number= models.CharField(max_length=50)
class_student_cities = models.ForeignKey(Students)
class_year = models.DateField()
def __unicode__(self):
return self.class_number
How can i show in the class_student_cities area the Students.student_city datas? I guess that about django-admin area. When i do it withclass_student_cities = models.ForeignKey(Students) i just see in that area the Students.student_name data (ex: John Smith). I want to see JUST Students.student_cities data (ex: NewYork). Can you give me a little example?
Should i use something like that:
class_student_cities = models.ForeignKey(Students.student_cities)
Many Thanks!
Try redifinition unicode method.
def __unicode__(self):
return self.student_city
So you'll see in the field student city.
Well, I tried to remake your application to set data with forms class. Something like this in admin.py in your application:
from django.contrib import admin
from django import forms
from myapp.models import *
class ClassRoomsAdminForm(forms.ModelForm):
class Meta:
model = ClassRoom
def __init__(self, *arg, **kwargs):
super(ClassRoomsAdminForm, self).__init__(*arg, **kwargs)
self.fields[' class_student_cities'].choices = [(csc.id,csc.student_city) for csc in Students.objects.all()
class ClassRoomsAdmin(admin.ModelAdmin):
form = ClassRoomsAdminForm
admin.site.register(ClassRooms,ClassRoomsAdmin)
Maybe you'll need to fix something, but I hope it will work. You will set init function to your forms, so in admin panel you set all choices to everything you keep in your Students model. csc.id you'll need to make this object iterable (cities aren't unique) and then you can choose everything from Students model to set in the field.
Hi I need really very very simple example. First my models:
#This my student models
from django.db import models
SEX_CHOICES= (
('M', 'Male'),
('F', 'Female'),
)
class Students(models.Model):
student_name = models.CharField(max_length=50)
student_sex = models.CharField(max_length=8, choices=SEX_CHOICES)
student_city = models.Charfield(max_length=50)
student_bio = models.TextField()
def __unicode__(self):
return self.student_name
O.K. Let see my Classes Model.
#This my Classes models
from django.db import models
from myproject.students.models import *
class Classes(models.Model):
class_number= models.CharField(max_length=50)
class_student_cities = models.ForeignKey(Students)
class_year = models.DateField()
def __unicode__(self):
return self.class_number
My classes/admin.py file looks like that:
from myproject.classes.models import *
from myproject.students.models import *
from django.contrib import admin
class ClassesChoiceField(Students):
class_student_cities = Classes.objects.get(id=1).class_student_cities.student_city
admin.site.register(Classes)
I get this error:
DoesNotExist at /admin/classes/classes/add/
Classes matching query does not exist.
How can i show in the class_student_cities area the Students.student_city datas? I guess that about django-admin area.
When i do it with ForeignKey(Students) i just see in that area the Students.student_name data :S. I'm really wondering how can I do it? Can you give me a little example?
Many Thanks!
See the documentation.
To get student_city from queryset, you can use:
Classes.objects.get(id=1).class_student_cities.student_city
And if you want to relate your foreignkey field not to primary key, you should use to_field argument
https://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.ForeignKey.to_field
It will be like:
class_student_cities = models.ForeignKey(Students, to_field='student_city')
There are a few problems -- basically things are 'not quite right', which is why you keep being referred to the docs.
Here is an example of what an admin.py should look like:
from django.contrib import admin
from articles.models import Article
def show_articletype_thumbnail(self):
return self.image.admin_thumbnail()
show_articletype_thumbnail.allow_tags=True
show_articletype_thumbnail.short_description = 'Image'
class ArticleAdmin(admin.ModelAdmin):
save_on_top = True
list_display = ['status', 'articletype', 'issue', 'penname', 'issue', show_articletype_thumbnail]
list_display_links = ['articletype']
list_filter = ['articletype', 'allow_comments', 'template', 'issue']
admin.site.register(Article, ArticleAdmin)