showing date from db in html date in django - django

How can i show date from db in django html template with input type date.
As You can see if we use input type 'date'. we can see the below widget showing in html. But if i want to it to show date from DB in below picture. Is there anyway i can do?
Showing like this, so user can see the current date from DB and change if needed.
forms.py
class ProfileUpdateForm(ModelForm):
#birthdate = forms.DateField(
# input_formats=['%dd-%mm-%yyyy'],
# widget=forms.DateInput(format='%dd-%mm-%yyyy', attrs={'type': "date"})
# )
class Meta:
model = User
fields = [
'email',
'full_name',
'address',
'city',
'state',
'postcode',
'phone_number',
'birthdate',
]
widgets = {
'full_name': Textarea(attrs={'cols': 35, 'rows': 1}),
'address': Textarea(attrs={'cols': 80, 'rows': 3}),
'city': Textarea(attrs={'cols': 35, 'rows': 1}),
'birthdate': forms.DateInput(format='%d %b %Y', attrs={'type':'date'}),
}

Related

Add additional field to response in pytest-django

I'm new to testing and I spent a day finding a solution for my problem but I couldn't find any.
this is my serializer
serilaizer.py
class LeadSerializer(serializers.ModelSerializer):
def create(self, validated_data):
user = self.context['user']
return Lead.objects.create(organizer=user.organizeruser, **validated_data)
class Meta:
model = Lead
fields = ['id', 'first_name', 'last_name', 'age', 'agent', 'category', 'description', 'date_added',
'phone_number', 'email', 'converted_date'
]
I have two types of users, organizer, and agent. organizer can create a lead but agent can't. and as you see I don't have organizer field. authenticated user will be added to the organizer field when a Lead is created.
test.py
def test_if_lead_exist_return_200(self, api_client, leads_factory, user_factory):
user = user_factory.create(is_organizer=True)
api_client.force_authenticate(user=User(is_staff=True))
lead = leads_factory.create()
serializer = LeadSerializer(context={'request': user})
print(serializer)
# here I can see the user
response = api_client.get(f'/api/leads/{lead.id}/', )
assert response.status_code == status.HTTP_200_OK
assert response.data == {
'id': lead.id,
'first_name': lead.first_name,
'last_name': lead.last_name,
'age': lead.age,
'organizer': lead.organizer.id,
'agent': lead.agent.id,
'category': lead.category.id,
'description': lead.description,
'date_added': lead.date_added,
'phone_number': lead.phone_number,
'email': lead.email,
'converted_date': lead.converted_date,
}
because there is no organizer field in the serialzier test won't pass and this is the result of the test
what can I do here? can I pass the organizer user to the response?
You should add the organizer into the fields.
class LeadSerializer(serializers.ModelSerializer):
class Meta:
model = Lead
# here I added the `organizer` field
fields = ['id', 'first_name', 'last_name', 'age', 'agent', 'category', 'description', 'date_added', 'phone_number', 'email', 'converted_date', 'organizer']
def create(self, validated_data):
...

Data Dissapearing in Django on validation

I am trying to create nested objects (documentregulation) when I create a Document object. To achieve this, I have overwritten the create method on the DocumentSerializer, as per Django Docs. However, when I attempt validated_data.pop('documentregulation_set'), it is empty, even when it is populated in the incoming request.data of my view. Is there something causing my incoming data to not be validated? How would I go about debugging this if so?
// serializers.py
class DocumentRegulationSerializer(serializers.ModelSerializer):
class Meta:
model = DocumentRegulation
fields = ('regulation',)
class DocumentSerializer(serializers.ModelSerializer):
documentregulation_set = DocumentRegulationSerializer(many=True, required=False)
class Meta:
model = Document
fields = ('documentregulation_set', 'id', 'name', 'file', 'text', 'uploaded_at')
extra_kwargs = {
'id': {'read_only': True},
'uploaded_at': {'read_only': True},
}
def create(self, validated_data):
documentregulation_set = validated_data.pop('documentregulation_set')
# create document first
document = Document.objects.create(**validated_data)
# serialize associated regulations
for documentregulation in documentregulation_set:
# get ID of newly-created document, use for relation
#documentregulation['regulation'] = documentregulation['id']
DocumentRegulation.objects.create(document=document, **documentregulation)
return document
//views.py
class DocumentView(generics.ListCreateAPIView):
def create(self, request):
#pprint(self.request.FILES['profile_pic'])
request.data['documentregulation_set'] = json.loads(request.data['documentregulation_set'])
request.data['documentdomain_set'] = json.loads(request.data['documentdomain_set'])
pprint(request.data)
document = DocumentSerializer(data=request.data)
if document.is_valid():
document.save()
return Response(document.data, status=status.HTTP_201_CREATED)
else:
return Response(document.errors, status=status.HTTP_400_BAD_REQUEST)
my incoming data (printed in request.data) looks like:
{'documentregulation_set': [{'label': 'Regulation 1',
'regulation': 2,
'value': 2},
{'label': 'Regulation 2',
'regulation': 4,
'value': 4}],
'file': <InMemoryUploadedFile: test.docx >,
'name': 'testing',
'text': 'test'}
but then my validated data prints out to be:
{'documentregulation_set': [],
'file': <InMemoryUploadedFile: test.docx >,
'name': 'testing',
'text': 'test'}
Problem seems to be with the validation of the documentregulation_set field in the DocumentSerializer serializer. But you can escape the validation in the Meta Class as:
class Meta:
model = Document
fields = '__all__'
extra_kwargs = {
'documentregulation_set': {'validators': []} # escape validation
}
If you need to write custom validators have a look at Writing custom validators
So the final serializer looks like:
class DocumentRegulationSerializere(serializers.ModelSerializer):
"""Serializers for DocumentRegulation object"""
class Meta:
model = DocumentRegulation
fields = ('regulation',)
class DocumentSerializer(serializers.ModelSerializer):
"""Serializer for Document objects"""
documentregulation_set = DocumentRegulationSerializere(many=True)
class Meta:
model = Document
fields = ('documentregulation_set', 'id', 'name', 'file', 'text', 'uploaded_at')
extra_kwargs = {
'id': {'read_only': True},
'uploaded_at': {'read_only': True},
'documentregulation_set': {'validators': []} # escape validation
}
def create(self, validated_data):
doc_reg = []
document_regulation_set = validated_data.pop('documentregulation_set')
document = Document.objects.create(**validated_data)
for document_regulation in document_regulation_set:
reg = DocumentRegulation.objects.create(**document_regulation)
reg.save()
doc_reg.append(reg)
document.documentregulation_set.add(reg)
return document
View
class DocumentView(generics.ListCreateAPIView):
"""List or create new Document ojects"""
queryset = Document.objects.all()
serializer_class = DocumentSerializer

Django: dynamic choice field for formsets

So I have a form
class DownloadForm(forms.Form):
title = forms.CharField()
device_family = forms.ChoiceField(label="Device Family",
widget=forms.Select(attrs={'class': 'form-control',
'data-toggle': 'select'}),
choices=LOG_ENTRY_TYPES, required=True
)
and in view.py I do
LOG_ENTRY_TYPES = (
('', 'All'),
('auth', 'Auth'),
('error', 'Error'),
('info', 'Info'),
('proxy', 'Proxy'),
)
DownloadFormSet = formset_factory(DownloadForm)
formsets = DownloadFormSet(initial=[
{'title': 'Django is now open source', 'device_family': LOG_ENTRY_TYPES},
{'title': 'Django source 2', 'device_family': LOG_ENTRY_TYPES},
{'title': 'Django source 3', 'device_family': LOG_ENTRY_TYPES}
])
This creates the device_family field but the LOG_ENTRY_TYPES choices are not generated. So how can I pass the LOG_ENTRY_TYPES choices to the device_family choices field so that the drop down shows the choices.

Django filter ManyToMany filed in query

I need to filter field with ManyToMany in queryset. There must stay only active Products
class Product(model.Model):
name = models.CharField()
active = models.BooleanField(blank=True, default=True)
class Package(model.Model):
name = models.CharField()
products = models.ManyToManyField(Product)
I tried something like this.
packages = Package.objects.all()
for package in packages:
active_products = package.products.filter(active=True)
package.products = active_products
but it updates my packages in database, when i need only change queryset.
expectation concept (do not really need nested structure, query set is fine):
packages = [
{'id': 1, 'name': 'First package', 'products': [
{'id': 1, 'name': 'first product', 'active': True},
{'id': 2, 'name': 'second product', 'active': True},
]},
{'id': 2, 'name': 'Second package', 'products': [
{'id': 2, 'name': 'first product', 'active': True},
{'id': 3, 'name': 'third product', 'active': True},
]},
{'id': 3, 'name': 'Third package', 'products': []}
]
I thought about creating a list of dictionaries from Packages by .values(), then iterate it and exclude all not active products.
Do you know any more elegant way to do it?
I'm not sure if this will work. But I think that we can play using the serializers.MethodSerialier. If it fails probably we can try to return another thing instead of the Productserializer directly.
class ProductSerializer(serializers.ModelSerializer):
class Meta:
model = Product
fields = ('id', 'name')
class PackageSerializer(serializers.ModelSerializer):
products = serializers.MethodSerializer()
class Meta:
model = Package
fields = ('id', 'name', 'products')
def get_products(self, obj):
products = obj.products.filter(active=True)
return ProductSerializer(products, many=True)
packages = Package.objects.filter(products__active=True)
serializer = PackageSerializer(packages, many=True)
# do something with the serializer
AFAIK, you won't get a nested output from Django :( But you will get something similar with .values() method of QuerySet class as,
results = Package.objects.filter(products__active=True).values('id', 'name', 'products__id', 'products__name', 'products__active')
filtered_result = [result for result in results if result['products__active']]

how to remove --------- from django Select widgets

How do I remove the ----- in my django ModelForm widgts?
documentation say to use empty_label but it is for SelectDateWidget
my form
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
exclude = ('copy', 'created', 'researcher', 'keywords', 'application_area', 'predominant_area')
widgets = {
'title':forms.TextInput(attrs={
'class':'form-control',
'placeholder': 'Titulo da oportunidade'
}),
'conclusion_date':forms.TextInput(attrs={
'class': 'form-control',
'type':'text',
'placeholder':'Data de conclusão'
}),
'category': forms.RadioSelect(attrs={
'class':'form-control'
}),
'result':forms.Select(attrs={
'class':'form-control'
}),
}
You can add default value for your select input then it will show default value initially.
For further reference:
https://docs.djangoproject.com/en/2.0/topics/forms/
https://docs.djangoproject.com/en/2.0/ref/forms/fields/