Django app to retrieve data from other apps models? - django

I have an app name sync which has a form created from a model that saves itself. I want to create another app called activity that retrieves the data from the sync models and other future apps. How can I do that in the activity views app?
This is my sync models.py
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
FS_CHOICES = (
('/path1/', 'P1'),
('/path2/', 'P2'),
('/path3/', 'P3'),
)
OPTIONS = (
('-n', 'TRY'),
)
class SyncJob(models.Model):
date = models.DateTimeField()
user = models.ForeignKey(User, unique=False)
source = models.CharField(max_length=3, choices=FS_CHOICES)
destination = models.CharField(max_length=3, choices=FS_CHOICES)
options = models.CharField(max_length=10, choices=OPTIONS)
class SyncJobForm(ModelForm):
class Meta:
model = SyncJob
fields = ['source', 'destination', 'options']
Ok, in activity views.py I have this:
from toolbox.sync.models import SyncJob
from django.shortcuts import render_to_response
def Activity()
sync_job = SyncJob.objects.get(id=03)
return render_to_response('base.html', {'sync_job': sync_job})
UPDATE: When I try to view the page it displays the error:
'function' object is not iterable

Just import it like any other python class.
So in your activity app you'd do something like this:
from sync.models import SyncJob
sync_job = SyncJob.objects.get(id=99)

Related

Model constraints are not working with Faker ( Django )

I am just starting to use pytest and faker for testing
while trying to create text for a field in testing db the constraints are being ignored and i don't know how to fix it.
models.py
from django.db import models
# Create your models here.
class Note(models.Model):
body = models.TextField(null=True, blank=True, max_length=5)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
factories.py
import factory
from faker import Faker
fake = Faker()
from mynotes_api.models import Note
class NoteFactory(factory.django.DjangoModelFactory):
class Meta:
model = Note
body = fake.text()
conftest.py
import pytest
from django.contrib.auth.models import User
from pytest_factoryboy import register
from tests.factories import NoteFactory
register(NoteFactory)
#pytest.fixture
def new_user1(db, note_factory):
note = note_factory.create()
return note
test_ex1.py
import pytest
def test_product(new_user1):
note = new_user1
print(note.body)
assert True
test output
the problem as visible in output is that the length of the text generated and being stored in the testing db is more than 5.
kindly guide me in this regard.
Iain Shelvington's advice to use a CharField is the main issue here. It will enforce the database constraint.
Django offers more types of validation that cannot be enforced by the database. These will not be checked on a model.save call:
Note that validators will not be run automatically when you save a
model, but if you are using a ModelForm, it will run your validators
on any fields that are included in your form.
See How validators are run.

Django - oscar show a field in dashboard

from oscar.apps.catalogue.abstract_models import AbstractProduct
from oscar.core.compat import AUTH_USER_MODEL
from django.db import models
class Product(AbstractProduct):
seller = models.ForeignKey(
AUTH_USER_MODEL,
on_delete=models.CASCADE,
null=True)
from oscar.apps.catalogue.models import *
I added this code to forked catalog model >
I want to show it in the dashboard,Image of dashboard and dropdown box I tried admin.site.register but it is not working.
This is the code for override of form , when I fork and overrtide it doesn't work but when I change the code in core it works .
from oscar.apps.dashboard.catalogue.forms import ProductForm
from oscar.core.loading import get_class, get_classes, get_model
from yourappsfolder.catalogue.models import Product
class SellerField(ProductForm):
class Meta(ProductForm.Meta):
model =Product
fields = [
'title','seller', 'upc', 'description', 'is_public', 'is_discountable', 'structure']
You have forked the form incorrectly. Calling your form class SellerField will not work. The form class needs to have exactly the same name as the core form, otherwise Oscar's loader will not find it. Change it like this:
from oscar.apps.dashboard.catalogue.forms import ProductForm as BaseProductForm
class ProductForm(BaseProductForm):
class Meta(BaseProductForm.Meta):
fields = ['title','seller', 'upc', 'description', 'is_public', 'is_discountable', 'structure']

How to query by joining a Django Model with other, on a non unique column?

I have the following models in my models.py file in my django project
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings
class CustomUser(AbstractUser):
pass
# add additional fields in here
class PDFForm(models.Model):
pdf_type=models.IntegerField(default=0)
pdf_name=models.CharField(max_length=100,default='')
file_path=models.FileField(default='')
class FormField(models.Model):
fk_pdf_id=models.ForeignKey('PDFForm', on_delete=models.CASCADE,default=0)
field_type=models.IntegerField(default=0)
field_page_number=models.IntegerField(default=0)
field_x=models.DecimalField(max_digits=6,decimal_places=2,default=0)
field_y=models.DecimalField(max_digits=6,decimal_places=2,default=0)
field_x_increment=models.DecimalField(max_digits=6,decimal_places=2,default=0)
class Meta:
ordering= ("field_page_number", "field_type")
class UserData(models.Model):
fk_user_id=models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,default=0)
field_type=models.IntegerField(default=0)
field_text=models.CharField(max_length=200,default='')
field_date=models.DateField()
Here is how the models are related
1) a pdfform contains a pdf form and path for it on the file system
2) A pdfform has multiple FormFields in it. Each field has attributes, and the specific one under discussion is field_type
3)The UserData model has user's data, so one User can have multiple rows in this table. This model also has the field_type column.
What I am trying to query is to find out all rows present in the Userdata Model which are present in the FormField Model ( matched with field_type) and that are of a specific PDFForm.
Given that the Many to Many relationship in django models cannot happen between no unique fields, how would one go about making a query like below
select a.*, b.* from FormField a, UserData b where b.fk_user_id=1 and a.fk_pdf_id=3 and a.field_type=b.field_type
I have been going through the documentation with a fine toothed comb, but obviously have been missing how django creates joins. what is the way to make the above sql statement happen, so I get the required dataset?
I think UserData is missing a relation to FormField, but if you had this relation you could do:
UserData.objects.filter(
fk_user_id=1, # Rename this to user, Django wilt automicly create a user_id column
form_field__in=FormField.objects.filter(
fk_pdf_id=<your pdfid> # same as fk_user_id
)
)
Edit updated models
When you use a ForeignKey you don't have to specify the _id or default=0, if you don't always want to fill the field its better to set null=True and blank=True
from django.contrib.auth.models import AbstractUser
from django.db import models
from django.conf import settings
class CustomUser(AbstractUser):
pass
# add additional fields in here
class FieldTypeMixin:
TYPE_TEXT = 10
TYPE_DATE = 20
TYPE_CHOISES = [
(TYPE_TEXT, 'Text'),
(TYPE_DATE, 'Date'),
]
field_type=models.IntegerField(default=TYPE_TEXT, choises=TYPE_CHOISES)
class PDFForm(models.Model):
pdf_type = models.IntegerField(default=0)
pdf_name = models.CharField(max_length=100,default='')
file_path = models.FileField(default='')
class FormField(models.Model, FieldTypeMixin):
pdf_form = models.ForeignKey('PDFForm', on_delete=models.CASCADE)
field_page_number = models.IntegerField(default=0)
field_x = models.DecimalField(max_digits=6,decimal_places=2,default=0)
field_y = models.DecimalField(max_digits=6,decimal_places=2,default=0)
field_x_increment = models.DecimalField(max_digits=6,decimal_places=2,default=0)
class Meta:
ordering = ("field_page_number", "field_type")
class SubmittedForm(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, models.CASCADE)
pdf_form = models.ForeignKey(PDFForm, models.CASCADE)
class SubmittedFormField(models.Model, FieldTypeMixin):
submitted_form = models.ForeignKey(SubmittedForm, models.CASCADE)
form_field = models.ForeignKey(FormField, models.CASCADE, related_name='fields')
field_text = models.CharField(max_length=200,default='')
field_date = models.DateField()
class Meta:
unique_together = [
['submitted_form', 'form_field']
]

How can you add a many to many field in Wagtail Admin?

I am trying to set make a footer for a Wagtail site that is included on every page, but I want to include a list of links (phone, email, social media). If I try the code below without the panel = [...] I can see it sort of works, but I am unable to add any items:
from wagtail.contrib.settings.models import BaseSetting, register_setting
from django import forms
class ContactInfo(models.Model):
CONTACT_CHOICES = (
('fas fa-phone', 'Phone'),
('fas fa-envelope', 'Email'),
('fab fa-facebook-f', 'Facebook'),
('fa-instagram', 'Instagram'),
('fab fa-linkedin', 'LinkedIn'),
('fab fa-twitter', 'Twitter'),
('fab fa-pinterest', 'Pinterest'),
('fab fa-github', 'GitHub'),
('fab fa-gitlab', 'GitLab'),
)
contact_type = models.CharField(choices=CONTACT_CHOICES, max_length=50)
contact_info = models.CharField(max_length=50)
info_prefix = models.CharField(max_length=10, editable=False)
def save(self, *args, **kwargs):
if self.contact_type == 'Phone':
self.info_prefix = 'tel:'
elif self.contact_type == 'Email':
self.info_prefix = 'mailto:'
else:
self.info_prefix = ''
#register_setting
class Contact(BaseSetting):
contact = models.ManyToManyField(ContactInfo)
panels = [
FieldPanel('contact', widget=forms.CheckboxSelectMultiple)
]
Is there a to add items to the M2M field? Is there a way to make lists of items in the Wagtail settings? Is there an easier way to make a footer that automatically is rendered on every page?
Each ContactInfo item (presumably) belongs to a single Contact, so this is a one-to-many relation rather than many-to-many. (A many-to-many relation in this case would mean that you have a shared pool of ContactInfo items previously defined through some other view, and you're selecting which ones to attach to the current Contact.)
In Wagtail, this would be defined using a ParentalKey on ContactInfo to point to the corresponding Contact, and rendered with an InlinePanel. (See the gallery image example from the Wagtail tutorial for an example.)
from django.db import models
from wagtail.admin.edit_handlers import FieldPanel, InlinePanel
from wagtail.core.models import Orderable
from wagtail.contrib.settings.models import BaseSetting, register_setting
from modelcluster.fields import ParentalKey
from modelcluster.models import ClusterableModel
class ContactInfo(Orderable):
CONTACT_CHOICES = (
# ...
)
contact = ParentalKey('Contact', on_delete=models.CASCADE, related_name='contact_links')
contact_type = models.CharField(choices=CONTACT_CHOICES, max_length=50)
contact_info = models.CharField(max_length=50)
# info_prefix handling omitted here for brevity
panels = [
FieldPanel('contact_type'),
FieldPanel('contact_info'),
]
#register_setting
class Contact(BaseSetting, ClusterableModel):
panels = [
InlinePanel('contact_links', label="Contact")
]

Select field for all models within a Django app

I am pretty new to Django.
I wanted to create a form for some user information. Depending on type of user informations, the fields should change... For example the users private address needs the fields name, street, zip and city. But if he wants something send to the company, there might be more fields like department or company name.
I want to implement something like this and create for each kind of input an extra model compact in a separate app.
Is there a way to get a select field with a list of all available models in this app.
Edit
Since I have some further problems, I add an example here
file: experiment/models.py
from django.db import models
from django.apps import apps
class BasicExperiment(models.Model):
date_created = models.DateTimeField(editable=False)
date_modified = models.DateTimeField(blank=True)
label_app = apps.get_app('labels')
label_types = apps.get_models(label_app)
file: labels/models.py
from django.db import models
class SILAC(models.Model):
lys0 = models.BooleanField('Lys-0', default=True)
lys4 = models.BooleanField('Lys-4', default=None)
lys8 = models.BooleanField('Lys-8', default=None)
arg0 = models.BooleanField('Arg-0', default=True)
arg6 = models.BooleanField('Arg-6', default=None)
arg10 = models.BooleanField('Arg-10', default=None)
class Meta:
verbose_name = 'SILAC Labeling'
In the shell it works as expected:
>>> from django.apps import apps
>>> app = apps.get_app('labels')
>>> for model in apps.get_models(app):
... model._meta.verbose_name
...
'SILAC Labeling'
Within my models.py I get the following error:
...
File "/Users/madejung/Documents/django_dev/cfproteomics/experiments/models.py", line 5, in <module>
class BasicExperiment(models.Model):
File "/Users/madejung/Documents/django_dev/cfproteomics/experiments/models.py", line 10, in BasicExperiment
label_app = apps.get_app('labels')
File "/Library/Python/2.7/site-packages/django/apps/registry.py", line 370, in get_app
"App '%s' doesn't have a models module." % app_label)
django.core.exceptions.ImproperlyConfigured: App 'labels' doesn't have a models module.
You could try this:
from django.db.models import get_app, get_models
app = get_app('my_application_name')
for model in get_models(app):
# do something with the model
Here there is more information Django get list of models in application