im still new in using django and python.. I am working on a drop-down dependency in HWname and HWType. I tried many codes but they didn't worked.. Here are my codes. Please help me :)
What I want to happen is for example in HWType I have Flexi and Flexi2, then in HWName I have Female and Male .. If I choose Flexi in HWType, only "Female" will be display in my HWName and If I choose Flexi2, HWName will display "Male" ..
Models.Py (Codes)
class HWName(models.Model):
hwnid = models.AutoField(max_length=6, primary_key=True, db_column='id')
hwnname = models.CharField(max_length=255, db_column='name')
class Meta:
db_table=u'hw_name'
def __unicode__(self):
return unicode((self.hwnname))
class HWType(models.Model):
hwtid = models.AutoField(max_length=6, primary_key=True, db_column='id')
hwtname = models.CharField(max_length=255, db_column='name')
class Meta:
db_table=u'hw_type'
def __unicode__(self):
return unicode((self.hwtname))
SCBT Inventory(advance search)
class Inventory (models.Model):
id = models.AutoField(max_length=6, primary_key=True, db_column='id')
hwname = models.ForeignKey(HWName, db_column='hw_name', default=1)
hwtype = models.ForeignKey(HWType, db_column='hw_type', default=1)
class Meta:
db_table=u'inventory'
def __unicode__ (self):
return unicode((self.assetnumber, self.serialnumber, self.hwname, self.hwtype))
Advanced Search Hardware Form
class AdvancedSearchForm (ModelForm):
hwname = forms.ModelChoiceField(queryset=HWName.objects.all(), label="Hardware Name")
hwtype = forms.ModelChoiceField(queryset=HWType.objects.all(), label="Hardware Type")
class Meta:
model = Inventory
exclude = ('id', 'assetnumber', 'serialnumber', 'remarks')
Views.Py (Codes)
def inventory (request):
##advanced search form:##
form = AdvancedSearchForm(request.POST or None)
##check if form is not empty##
hwname = request.GET.get('hwname', 0)
hwtype = request.GET.get('hwtype',0)
if hwname == 'None':
hwname = ''
if hwtype == 'None':
hwtype = ''
try "django-smart-selects"
that looks like what you need
https://github.com/digi604/django-smart-selects
Related
When importing a file I want to skip all of the new rows that doesn't exist, and only update and change the ones that already exists, I've been trying for days to solve this problem, any ideas will help.
https://ibb.co/1Gw4Q19
also the file type is ".xls" or ".xlsx"
here's my code:
models.py:
class Author(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Category(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField('Book name', max_length=100)
author = models.ForeignKey(Author, blank=True, null=True, on_delete=models.CASCADE)
author_email = models.EmailField('Author email', max_length=75, blank=True)
imported = models.BooleanField(default=False)
published = models.DateField('Published', blank=True, null=True)
price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True)
categories = models.ManyToManyField(Category, blank=True)
def __str__(self):
return self.name
admin.py:
class BookResource(resources.ModelResource):
class Meta:
model = Book
import_id_field = 'id'
import_id_fields = ('id',)
fields = ('id', 'name', 'price',)
skip_unchanged = True
report_skipped = True
dry_run = True
class CustomBookAdmin(ImportMixin, admin.ModelAdmin):
resource_class = BookResource
# tried to override it like so but it didn't work
def skip_row(self, instance, original):
original_id_value = getattr(original, self._meta.import_id_field)
instance_id_value = getattr(instance, self._meta.import_id_field)
if original_id_value != instance_id_value:
return True
if not self._meta.skip_unchanged:
return False
for field in self.get_fields():
try:
if list(field.get_value(instance).all()) != list(field.get_value(original).all()):
return False
except AttributeError:
if field.get_value(instance) != field.get_value(original):
return False
return True
So if you want to skip any rows in the import file which do not already exist in the database, then you can ignore any rows which don't have a pk (i.e. have not previously been persisted):
Just add the following to your BookResource sub class
def skip_row(self, instance, original):
return getattr(original, "pk") is None
I hope this works - let me know if I've misunderstood anything.
The full solution exists here
To only update existing items while ignoring any new item you can use:
# Do not import any new items. Only update records
def skip_row(self, instance, original):
if original.id:
return False
return super(BookResource, self).skip_row(instance, original)
To import only new items while preventing updates you can use:
# Only import new items. Do not update any record
def skip_row(self, instance, original):
if not original.id:
return False
return True
This assumes import_id_fields = ('id',) and resource is called BookResource
the problem about 2 things ; First of all in admin panel and webpage foreign keys are shown as object(1) ,Yes I know the solution of this we use str stuff but when I try to compare id of them it takes the value of str function result let me show in code;
Im checking logged in user's connected company id that equals to only students who are connected with same company
model.py - Student
class Student(models.Model):
id = models.AutoField(primary_key=True, verbose_name='StudentID')
parentid = models.ForeignKey(Parent, on_delete=models.CASCADE, verbose_name='ParentID')
companyid = models.ForeignKey(Company, on_delete=models.CASCADE, verbose_name='CompanyID')
classid = models.ForeignKey(Classes, on_delete=models.CASCADE, verbose_name='ClassID')
gender = models.CharField(max_length=1, default='N', verbose_name='Gender')
name = models.CharField(max_length=30, verbose_name='Name')
surname = models.CharField(max_length=30, verbose_name='Surname')
dob = models.DateTimeField(verbose_name='Doğum Yılı')
bloodtype = models.ForeignKey(BloodType, on_delete=models.CASCADE, verbose_name='Blood Type')
status = models.BooleanField(verbose_name='State')
list_display = ('id', 'parentid', 'companyid', 'classid', 'gender', 'name', 'surname', 'dob', 'bloodtype', 'status')
def __str__(self):
return "%s %s - %s" % (self.name, self.surname, self.gender)
model.py - Company
class Company(models.Model):
id = models.AutoField(primary_key=True, verbose_name='CompanyID')
name = models.CharField(
max_length=100, verbose_name='Company Name')
contactname = models.CharField(max_length=30)
contactsurname = models.CharField(
max_length=30)
address = models.CharField(max_length=200)
city = models.CharField(max_length=20)
phone = models.CharField(max_length=12)
weburl = models.URLField(max_length=80)
email = models.CharField(max_length=80)
studentcapacity = models.BigIntegerField(verbose_name='Student Capacity')
classcapacity = models.BigIntegerField(verbose_name='Class Capacity')
notes = models.TextField(max_length=200)
status = models.BooleanField(verbose_name='State')
list_display = ('id', 'name', 'contactname', 'contactsurname', 'address', 'city', 'phone',
'weburl', 'email', 'studentcapacity', 'classcapacity', 'notes', 'status')
def __str__(self):
return "%s - %s" % (self.id, self.name)
views.py
#login_required()
def student_update(request, pk):
student = get_object_or_404(Student, pk=pk)
usercompanyid = UserProfile.objects.filter(userid=request.user.id).only('companyid')
print('before control')
a = usercompanyid.values_list('companyid', flat=True)[0]
print(a)
print(student.companyid)
if student.companyid == a:
print('passed if')
if request.method == 'POST':
form = StudentForm(request.POST, instance=student)
else:
form = StudentForm(instance=student)
return save_student_form(request, form, 'student_update_partial.html')
else:
return view_404(request)
at if state " student.companyid == a: " = Company ID - Company Name , output: 1 -Test CompanyName = 1 , I need it to return only field I call which is companyid, I know it is allias to "companyID - companyName". Is it possible to fix this with another way , I'm not pro of django python , just trying to do some project for learning if it's a dump question sorry for all :)
When you do this:
companyid = models.ForeignKey(...)
The database schema would actually have a field name of companyid_id.
So in your case, if you want to compare object IDs then you actually need to do this:
if student.companyid_id == a:
To avoid confusion, I would advise you not to append the 'id' part to your Django model field names.
There's a lot of unnecessary messing around with only and values here. No need for any of that. Just compare the objects directly:
def student_update(request, pk):
student = get_object_or_404(Student, pk=pk)
if student.companyid == request.userprofile.companyid:
...
As an aside, you shouldn't call your foreign keys "companyid", "parentid" etc; they're not IDs, they're objects. Call them "company", "parent" etc.
I created a form view and when I want to save a form with two modules I see "IntegrityError". Please help, Thank you in advance
class Place(models.Model):
LocalName = models.CharField('Nazwa Lokalu', max_length=200)
slug = models.SlugField('Link', max_length=100, default="")
LocalImg = models.ImageField('Zdjęcie Lokalu',
upload_to='Place/static/locals/img', blank=True, max_length=20000)
LocalAdress = models.CharField('Adres', max_length=500)
LocalNumberPhone = models.CharField('Numer telefonu', max_length=9)
LocalHours = models.TextField(verbose_name='Godziny otwarcia',
max_length=20000)
def get_aboslute_url(self):
return reverse("place:place_create", kwargs={'id': self.id})
class Meta:
verbose_name = "Lokal"
verbose_name_plural = "Lokale"
def __str__(self):
return self.LocalName
class Menu(models.Model):
place = models.ForeignKey(Place, on_delete=models.CASCADE,
related_name="place", default="")
Dinner = models.CharField("Nazwa potrawy",blank=True, default="",
max_length=200)
DinnerComponents = models.CharField("Składniki",blank=True, default="",
max_length=20009)
PizzaPrice = models.CharField("Rozmiar i cena Pizzy",
help_text="np.Mała-10zł", default="", blank=True, max_length=300)
Price = models.DecimalField("Cena",default="00", max_digits=5,
decimal_places=2)
class Meta:
verbose_name = "Menu"
verbose_name_plural = "Menu"
views.py
def create_place(request):
form = PlaceForm()
sub_form = MenuForm()
if request.POST:
form = PlaceForm(request.POST)
sub_form = MenuForm(request.POST)
if form.is_valid() and sub_form.is_valid():
place = form.save(commit=False)
place.location = sub_form.save()
place.save()
context = {
'form': form,
'sub_form': sub_form
}
return render(request, 'posts/layout.html', context)
Forms.py
class PlaceForm(forms.ModelForm):
class Meta:
model = Place
fields = ('LocalName', 'LocalAdress', 'LocalNumberPhone','LocalHours',)
class MenuForm(forms.ModelForm):
class Meta:
model = Menu
fields = ('Dinner','DinnerComponents','DinerCategory', 'Price',)
After filling in the form and clicking submit, an error will appear "NOT NULL constraint failed: posts_menu.place_id"
You have to first save a Place then assign the saved place to the Menu and finally save the menu.
if form.is_valid() and sub_form.is_valid():
place = form.save()
menu = sub_form.save(commit=False)
menu.place = place
menu.save()
That's because a Menu needs a place foreign key otherwise it cannot be saved.
(Note: why do you mix snake_case and CamelCase for your field names? It's terribly difficult to know how your model's properties are called. Python's convention is snake_case for all properties/methods/variables)
I am trying to create a form in Admin site that uses two fields from two different tables (Employee, Product) as input (single select & multi-select) and make it available for admin user selection and write this to another table (JobQueue).
Following is my code.
models.py
class Employee(models.Model):
id = models.IntegerField(primary_key=True, verbose_name='Employee Code')
name = models.CharField(max_length=200, verbose_name='Employee Name')
def __str__(self):
return self.name
class Product(models.Model):
STATUS = (('New', 'New'), ('Go', 'Go'), ('Hold', 'Hold'), ('Stop', 'Stop'))
code = models.IntegerField(primary_key=True, max_length=3, verbose_name='Product Code')
name = models.CharField(max_length=100, verbose_name='Product Name')
def __str__(self):
return self.name
class JobQueue(models.Model):
emp_name = models.CharField(max_length=200, default='1001')
product_code = models.CharField(max_length=200, default='100')
admin.py:
class JobQueueAdmin(admin.ModelAdmin):
form = JobQueueForm
fieldsets = (
(None,{'fields': ('emp_name', 'product_code'),}),)
def save_model(self, request, obj, form, change):
super(JobQueueAdmin, self).save_model(request, obj, form, change)
forms.py:
class JobQueueForm(forms.ModelForm):
# Single select drop down
emp_name = forms.ModelChoiceField(queryset=Employee.objects.all(), widget=forms.ChoiceField())
# Multiselect checkbox
product_code = forms.MultiValueField(queryset=Product.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False)
def save(self, commit=True):
return super(JobQueueForm, self).save(commit = commit)
class Meta:
model = JobQueue
fields = ('emp_name', 'product_code')
When I start the web-server, I get the following error:
AttributeError: 'ModelChoiceField' object has no attribute 'to_field_name'
Could someone please help me how do I let the user to pick the values from JobQueueForm and save the same in JobQueue table ?
I am new in DJango. I have a database with three tables:
> -CRP
> - SubComponents of a CRP
> - Objectives of a SubComponent of a CRP.
I have the following models:
class period(models.Model):
period_code = models.IntegerField(primary_key=True,verbose_name='Period code')
period_desc = models.CharField(max_length=45,verbose_name='Period description')
period_current = models.IntegerField(verbose_name='Current period')
def __unicode__(self):
return self.period_desc
class Meta:
db_table = 'period'
class crp(models.Model):
crp_code = models.CharField(max_length=3,primary_key=True,verbose_name='CRP code')
crp_desc = models.CharField(max_length=45,verbose_name='CRP description')
def __unicode__(self):
return self.crp_desc
class Meta:
db_table = 'crp'
class subcomponent(models.Model):
crp_code = models.ForeignKey(crp,db_column='crp_code',related_name='subcomponent_crp_code',to_field='crp_code',primary_key=True,verbose_name='CRP code')
subc_code = models.CharField(max_length=3,primary_key=True,verbose_name='SubComponent Code')
subc_desc = models.CharField(max_length=45,verbose_name='SubComponent Description')
def __unicode__(self):
return self.subc_desc
class Meta:
db_table = 'subcomponent'
class objective(models.Model):
crp_code = models.ForeignKey(subcomponent,db_column='crp_code',related_name='objective_crp_code',to_field='crp_code',primary_key=True,verbose_name='CRP code')
subc_code = models.ForeignKey(subcomponent,db_column='subc_code',related_name='objective_subc_code',to_field='subc_code',primary_key=True,verbose_name='SubComponent Code')
obj_year = models.ForeignKey(period,db_column='obj_year',related_name='objective_obj_year',to_field='period_code',primary_key=True,verbose_name='Objective year')
obj_code = models.CharField(max_length=7,primary_key=True,verbose_name='Objective code')
obj_desc = models.CharField(max_length=45,verbose_name='Objective description')
def __unicode__(self):
return self.obj_desc
class Meta:
db_table = 'objective'
All works fine for the "subcomponent" model (reference to CRP); in the administration of "subcomponent" the user can pull down a CRP and add a subcomponent to it.
However, the model "objective" reference the model "subcomponent". In the administration of "objective" I would like the user to pull down and select a CRP, then filter the subcomponents of that CRP also in a pull down list. How can I do this?
Many thanks,
Carlos.
Take a look on django-smart-selects