I try compare string from AJAX Request with data( name ) at my Database, but my queryset don't working:
def create_name(request):
if request.method == 'POST':
name = request.POST['name']
for i in Name.objects.all():
if i.name != name:
Name.objects.create(
name=name,
)
return HttpResponse(status=200)
Console:
In [3]: for e in Name.objects.all()
...: print(e.name)
Michael
Jack
Chris
Comparing don't working and name will storing at my DB.
Name should be unique.
Thanks in advance!
by your current logic you create new instance for all others rows except equal to current post name, you can try get_or_create
def create_name(request):
if request.method == 'POST':
name = request.POST.get('name')
obj, created = Name.objects.get_or_create(name=name)
if created:
return HttpResponse(status=201)
return HttpResponse(status=200)
more details here get-or-create
Related
I've created an API with rest_framework and can receive API calls that updates the database, but I can't figure how to query the database and return any row where the field "Endtime" is NULL.
In the function below I'm updating the database with the received JSON-data and this fails to return any result where the value is NULL for Endtime. Below is the error I get. How should I write the view to return rows where endtime column is NULL?
ValidationError at /durationupdate/
['“NULL” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
Request Method: POST
Request URL: http://127.0.0.1:8000/durationupdate/
Django Version: 4.1.1
Exception Type: ValidationError
Exception Value:
['“NULL” value has an invalid format. It must be in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format.']
views.py
`
#api_view(['POST', 'GET'])
def durationUpdate(request):
if request.method == 'POST':
serializer = RigstateSerializer(data=request.data)
wherenull = Rigstate.objects.get(endtime='NULL')
wherenullserializer = DurationSerializer(wherenull, many=True)
if serializer.is_valid():
serializer.save()
return Response(wherenullserializer.data)
`
models.py
`
class Rigstate(models.Model):
rigname = models.CharField(max_length=255)
rigmode = models.IntegerField(default=0)
starttime = models.DateTimeField()
endtime = models.DateTimeField(blank=True, null=True)
duration = models.IntegerField(default=0)
def __str__(self):
return self.rigname
`
I've tried changing from 'NULL' to NULL but then I get a different error
You should your endtime write only and override to_represenation method like this.
class RigstateSerializer(serializer.ModelSerializer):
class Meta:
model = Rigstate
fields = '__all__'
extra_kwargs = {'endtime': {'write_only': True}}
def to_representation(self, instance):
data = super().to_representation(instance)
if instance.endtime:
data['endtime'] = instance.endtime.strftime(#write you required format here)
return data
Changed name to a more appropriate (DurationList)
views.py
#api_view(['GET'])
def durationList(request):
if request.method == 'GET':
duration = Rigstate.objects.values_list('endtime')
wherenullserializer = DurationSerializer(duration, many=True)
return Response(wherenullserializer.data)
Most changes were in serializers.py
class DurationSerializer(serializers.ModelSerializer):
class Meta:
model = Rigstate
endtime = serializers.DateTimeField(allow_null=True)
fields = ('endtime',)
Now I only get columns where entime is null, and only the endtime value
I'm learning how to use django rest API for my project. I created a stored_procedure on my postgresql and I want to incorporate it to my project
I did make one but without serializers or any related to the rest API, just plain django
here's my views.py without the rest_framework
def add(request):
if request.method == "POST":
if request.POST.get('office_id') and request.POST.get('sem') and request.POST.get('sy') and request.POST.get('incident_details') and request.POST.get('resolution') and request.POST.get('studid'):
saverec = Clearanceinsert()
saverec.office_id = request.POST.get('office_id')
saverec.sem = request.POST.get('sem')
saverec.sy = request.POST.get('sy')
saverec.remarks = request.POST.get('incident_details')
saverec.resolution = request.POST.get('resolution')
saverec.studid = request.POST.get('studid')
cursor = connection.cursor()
email = request.user.userid
cursor.execute("select add_clearance_item('"+saverec.office_id+"','"+saverec.sem+"','"+saverec.sy+"','"+saverec.remarks+"','"+saverec.resolution+"','"+email+"','"+saverec.studid+"')")
return render(request, 'clearance/index.html')
else:
return render(request, 'clearance/add.html')
views.py using rest_framework
#api_view(['POST'])
def saveitem(request):
if request.method == 'POST':
saveserialize = Insertserialize(data=request.data)
if saveserialize.is_valid():
cursor = connection.cursor()
cursor.execute("select add_clearance_item('"+saveserialize.office_id+"','"+saveserialize.sem+"','"+saveserialize.sy+"','"+saveserialize.remarks+"','"+saveserialize.resolution+"','"+saveserialize.studid+"')")
return Response(saveserialize.data, status=status.HTTP_201_CREATED)
return Response(saveserialize.data, status=status.HTTP_400_BAD_REQUEST)
When using rest_framework code, It's throwing an error 'Insertserialize' object has no attribute 'office_id'
serializer.py
class Insertserialize(serializers.ModelSerializer):
class Meta:
model = ClearanceItem
fields = [
'office_id',
'sem',
'sy',
'remarks',
'resolution',
'studid'
]
hope someone can help me with this
I am writing an api for an image labelling game using Django Rest Framework's APIView class.
The game implies that a user will see a picture (resource) and label it with one or more labels (tagging). Since the picture is sent an an object through the GET request and a label references the picture the label was posted for, I somehow need to access the id of the picture when storing a label in the database.
Currently, I am testing my POST request, which is pretty standard:
def post(self, request, *args, **kwargs):
tag_serializer = TagSerializer(data=request.data)
tagging_serializer = TaggingSerializer(data=request.data)
if tagging_serializer.is_valid(raise_exception=True):
tagging_serializer.save(tagging=request.data)
return Response({"status": "success", "data": tagging_serializer.data}, status=status.HTTP_201_CREATED)
else:
return Response({"status": "error", "data": tag_serializer.errors}, status=status.HTTP_400_BAD_REQUEST)
I am handling most of the logic in the TaggingSerializer:
class TaggingSerializer(serializers.ModelSerializer):
tag = TagSerializer(required=False, write_only=False)
resource_id = serializers.PrimaryKeyRelatedField(queryset=Resource.objects.all(),
required=True,
source='resource',
write_only=False)
gameround_id = serializers.PrimaryKeyRelatedField(queryset=Gameround.objects.all(),
required=False,
source='gameround',
write_only=False)
user_id = serializers.PrimaryKeyRelatedField(queryset=CustomUser.objects.all(),
required=False,
source='user',
write_only=False)
class Meta:
model = Tagging
fields = ('id', 'user_id', 'gameround_id', 'resource_id', 'tag', 'created', 'score', 'origin')
depth = 1
def create(self, validated_data):
"""Create and return a new tagging"""
user = None
request = self.context.get("request")
if request and hasattr(request, "user"):
user = request.user
score = 0
tag_data = validated_data.pop('tag', None)
if tag_data:
tag = Tag.objects.get_or_create(**tag_data)[0]
validated_data['tag'] = tag
if not Tag.objects.all().filter(name=tag.name).exists():
score = 0
elif Tag.objects.all().filter(name=tag.name).exists():
score += 5
elif Tag.objects.all().filter(name=tag.name) in coordinated_gameround_tags:
score += 25
tagging = Tagging(
user=user,
gameround=validated_data.get("gameround"),
# resource=request.query_params['resource'].id,
resource=validated_data.get("resource"),
tag=validated_data.get("tag"),
created=datetime.now(),
score=score,
origin=""
)
tagging.save()
return tagging
def to_representation(self, instance):
rep = super().to_representation(instance)
rep['tag'] = TagSerializer(instance.tag).data
return rep
I have tried accessing the resource from the get request with request.query_params but this also does not seem to work. When testing my post request in Postman I keep getting the error "resource_id": ["This field is required"].
Am I using request.query_params the wrong way? Is there another way to access this particular object that I don't know of? How else can I solve this?
I got an Exception
Got AttributeError when attempting to get a value for field weight on serializer WeightHistorySerializer.
The serializer field might be named incorrectly and not match any attribute or key on the QuerySet instance.
Original exception text was: 'QuerySet' object has no attribute 'weight'.
When I tried to retrive data.
models.py
class WeightHistory(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
weight = models.FloatField(null=False, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
serializers.py
class WeightHistorySerializer(serializers. HyperlinkedModelSerializer):
class Meta:
model = WeightHistory
fields = (
'id',
'weight',
'user_id',
'created_at'
)
read_only_fields = ('id',)
views.py
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history)
return Response(serializer.data)
If it change to
weight_history = WeightHistory.objects.get(user_id=user_id)
It returns only one row, But I want all the rows with given user_id. So, What should I do to get all list with given user_id.
'QuerySet' object has no attribute 'weight'.
Yes. QuerySet is a Set, a list of objects.
<QuerySet [<Object1>, <Object2>,..]>
And that list has no attribute weight. Instead, the objects inside the QuerySet has the attribute weight.
weight_history = WeightHistory.objects.filter(user_id=user_id)
filter returns a QuerySet, a list of WeightHistory objects with user_id=user_id.
And you are trying to serialize the list as a single object.
Instead of this:
serializer = WeightHistorySerializer(weight_history)
Do this:
serializer = WeightHistorySerializer(weight_history, many=True)
many=True tells the serializer that a list of objects being passed for serialization.
Moreover,
try:
weight_history = WeightHistory.objects.filter(user_id=user_id)
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
This doesn't throw an exception at all. filter returns an empty QuerySet if no objects exist. <QuerySet []>.
So the final code is:
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
weight_history = WeightHistory.objects.filter(user_id=user_id)
if weight_history.count()<1:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history, many=True)
return Response(serializer.data)
views.py
def weight_history_detail(request, user_id):
# Retrieve, update or delete a weight_history/detail.
try:
weight_history = WeightHistory.objects.get(user_id=user_id) #get
except WeightHistory.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == 'GET':
serializer = WeightHistorySerializer(weight_history)
return Response(serializer.data)
use get instead of filter it will solve you error
So in this formset the first field saves & updates just fine... but when I want to add a new object, it doesn't work out so well.
#Views.py
def edit_auto(request):
car = Auto.objects.filter(user=request.user)
CarFormSet = modelformset_factory(Auto, form=AutoForm, max_num=3)
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
formset.user = request.user
formset.save()
return render_to_response('manage_users.html', {'message':'Success! The user has been updated!'}, context_instance=RequestContext(request))
else:
formset = CarFormSet(queryset=car)
return render_to_response('mycar.html', locals(), context_instance=RequestContext(request))
#forms.py
class AutoForm(forms.ModelForm):
class Meta:
model = Auto
user = Auto.user
exclude = ('user',)
Is it something in the template? If it was a single instance of the form, form.user = request.user normally saves but this doesn't. Any suggestions? Thank you for your help.
For the user-assigning step, just iterate over the formset.
...
if request.method == 'POST':
formset = CarFormSet(request.POST, request.FILES, queryset=car)
if formset.is_valid():
formset.save(commit=False)
for form in formset:
form.user = request.user
formset.save()
...