I am trying to get follower system to work but it just wont work
class Followers(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
another_user = models.ManyToManyField(User, related_name='another_user')
def __str__(self):
return self.user.name
def profile(request, user_name):
user_obj = User.objects.get(username=user_name)
session_user, create = User.objects.get(username=user_name)
session_following, create = Followers.objects.get_or_create(user=session_user)
following = Followers.objects.get_or_create(user=session_user.id)
check_user_followers = Followers.objects.filter(another_user=user_obj)
is_followed = False
if session_following.another_user.filter(username=user_name).exists() or following.another_user.filter(username=user_name).exists():
is_followed=True
else:
is_followed=False
param = {'user_obj': user_obj,'followers':check_user_followers, 'following': following,'is_followed':is_followed}
if 'user' in request.session:
return render(request, 'users/profile2.html', param)
else:
return redirect('index')
I am getting the error:
AttributeError at /profile/chandan
'tuple' object has no attribute 'another_user'
get_or_create(…) [Django-doc] returns a 2-tuple with as first item the object, and as second item a boolean that indicates if the object was created (True), or already in the database.
You can make use of iterable unpacking to set the boolean to a "throwaway" variable:
# ↓ throw away the second item of the 2-tuple
session_following, __ = Followers.objects.get_or_create(user=session_user)
following, __ = Followers.objects.get_or_create(user=session_user)
Related
I tried to use generic relation in django project. but it gives attribute error.
Generic relation is between UniqueSourcePresenter and UniqueDbSource
i have an instance of TextTable which has a foreignkey attribute for UniqueSourcePresenter i tried to use reverse relation as self.presenter.texttable in UniqueDbSource's instance method. but it gives error es below
File "/usr/src/app/apps/tableau/models/source.py", line 191, in create_datum
backend | if self.presenter.texttable is not None:
backend | AttributeError: 'GenericRelatedObjectManager' object has no attribute 'texttable'
My models are like follows
class UniqueSourcePresenter(models.Model):
"""
Generic Relation Manager of all types of source
"""
# Below the mandatory fields for generic relation
limit = models.Q(app_label = 'tableau', model = 'UniqueDbSource'.lower()) | models.Q(app_label = 'tableau', model = 'UniqueAPISource'.lower())
content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE, limit_choices_to = limit)
object_id = models.PositiveIntegerField()
content_object = GenericForeignKey()
pass
class DataSource(models.Model):
pass
class UniqueSource(DataSource):
presenter = GenericRelation(UniqueSourcePresenter)
class Meta:
abstract = True
class UniqueDbSource(UniqueSource):
"""
THIS CLASS ADDED TO CONTENTTYPE
"""
def create_datum(self):
""" THIS METHOD CALLED WITH SIGNAL """
d = DatumDb()
d.title = f"{self.title}_datum"
if self.presenter.texttable is not None: ## THIS LINE GIVES ERROR
d.connector = self.presenter.texttable.init_source.data.connector
query = self.presenter.texttable.init_source.data.query
elif self.presenter.charttable is not None:
d.connector = self.charttable.presenter.init_source.data.connector
query = self.charttable.presenter.init_source.data.query
query.pk = None
query.save()
d.query = query
d.save()
self.data = d
pass
def create_presenter(self):
p = UniqueSourcePresenter()
p.content_type = ContentType.objects.get(app_label='tableau', model='UniqueDbSource'.lower())
p.object_id = self.id
p.save()
class Table(models.Model):
unique_source = models.OneToOneField(UniqueSourcePresenter, on_delete=models.CASCADE, null=True, blank=True, related_name="%(class)s")
class Meta:
abstract = True
class TextTable(Table):
pass
def create_unique_source(self):
"""
create a unique source object if created
and add selfs
"""
if self.init_source.content_type.model == 'InitialDbSource'.lower():
us = UniqueDbSource()
us.title = f"{self.title}_unique_source"
us.save()
self.unique_source = us.presenter
elif self.init_source.content_type.model == 'InitialAPISource'.lower():
us = UniqueAPISource()
us.title = f"{self.title}_unique_source"
us.save()
self.unique_source = us.presenter
pass
I added pass words where is not about my problem.
EDIT:
signal.py
#receiver(post_save, sender=UniqueDbSource)
#receiver(post_save, sender=UniqueAPISource)
def after_unique_source_save(sender, instance, created, **kwargs):
if created:
instance.create_datum()
instance.create_presenter()
instance.__class__.objects.filter(id=instance.id).update(
data=DatumDb.objects.all().last())
else:
pass
#receiver(post_save, sender=TextTable)
def after_table_save(sender, instance, created, **kwargs):
if created:
pass
instance.create_unique_source()
pass
if created:
TextTable.objects.filter(id=instance.id).update(
unique_source=UniqueSourcePresenter.objects.all().last()
) # may you can also give a good advice for this line
I have written this code. Every time I assign a variable I am getting "local variable 'obj' referenced before assignment". I don't know where I did wrong.
This is my view.py file:
def blog_detail(request, slug):
queryset = Blog.objects.filter(slug=slug)
if queryset.count() == 1:
obj = queryset.first()
templates = "temp_app.html"
context = {"object": obj}
return render(request, templates, context)
Here is my models.py file
class Blog(models.Model):
title = models.TextField()
slug = models.SlugField()
content = models.TextField(null=True, blank=True)
every time I run the server I am getting UnboundLocalError.
bt if I use "queryset" without assigning it into "obj" I don't get the error.
I am getting the error after assigning the "queryset" in "obj". Where am I doing wrong?
That mean you should add the obj variable before if conditional. In your case, the result of queryset variable is not 1.
queryset = Blog.objects.filter(slug=slug)
if queryset.count() == 1:
obj = queryset.first()
to;
obj = None # or whatever your need.
queryset = Blog.objects.filter(slug=slug)
if queryset.count() == 1:
obj = queryset.first()
or;
queryset = Blog.objects.filter(slug=slug)
if queryset.count() == 1:
obj = queryset.first()
else:
obj = None # or whatever your need.
I want to return a JsonResponse/HttpResponse from my Django views function. However I am getting 'str' object has no attribute 'META' error. The code for the function is given below.
def search(request):
queryset_list = Influencer.objects.orderby('username')
if 'username' in request.GET:
username = request.GET['username']
if username:
queryset_list = queryset_list.filter(username__iexact=username)
#Full Name
if 'fullname' in request.GET:
fullname = request.GET['fullname']
if fullname:
queryset_list = queryset_list.filter(full_name__iexact=fullname)
context = {
'listings':queryset_list,
'values':request.GET
}
filtered_data = serializers.serialize("json",context)
return JsonResponse(filtered_data)
Instead of serializing the context I serialized the query_list obtained and the function worked correctly.
The code after the last if statement should be this.
serialized_list = serializers.serialize('json',queryset_list)
return HttpResponse(serialized_list, content_type='application/json')
I have the following view -
class DeployFilterView(generics.ListAPIView):
serializer_class = DefinitionSerializer
def get_queryset(self):
jobname = self.request.GET.get('jobname')
if jobname.count("\\") == 1:
jobname = jobname.replace("\\", "")
queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_name=jobname).exclude(jobmst_prntname__isnull=False, jobmst_dirty='X')
else:
parent, job = jobname.rsplit('\\', 1)
queryset = Jobmst.objects.db_manager('Admiral').filter(jobmst_prntname=parent, jobmst_name=job).exclude(jobmst_dirty='X')
return queryset
In that view there's a value field called "jobmst_runbook" which has a character that doesn't translate with the DRF XML renderer. What I'd like to be able to do is scan the queryset for a particular character - SOH or \u0001
If it finds this character I want to remove it before doing the return queryset
I solved this by doing the logic in my serializer. The serializer is now looking for the object that's causing the failure and stripping out the character.
class DefinitionSerializer(serializers.ModelSerializer):
runbook_url = serializers.SerializerMethodField('get_url')
# dependencies = serializers.RelatedField(many=True)
jobdep = serializers.HyperlinkedRelatedField(
source='jobdep_set', # this is the model class name (and add set, this is how you call the reverse relation of bar)
view_name='jobdep-detail' # the name of the URL, required
)
# triggers = serializers.RelatedField(many=True)
trgmst = serializers.HyperlinkedRelatedField(
source='trgmst_set', # this is the model class name (and add set, this is how you call the reverse relation of bar)
view_name='trgmst-detail' # the name of the URL, required
)
class Meta:
model = Jobmst
resource_name = 'jobmst'
depth = 2
fields = ('jobmst_id', 'jobmst_type', 'jobmst_prntid', 'jobmst_active', 'evntmst_id',
'jobmst_evntoffset', 'jobmst_name', 'jobmst_mode', 'jobmst_owner', 'jobmst_desc',
'jobmst_crttm', 'jobdtl_id', 'jobmst_lstchgtm', 'runbook_url', 'jobcls_id', 'jobmst_prntname',
'jobmst_alias', 'jobmst_dirty', 'job_dependencies', 'job_events')
def get_url(self, obj):
if obj.jobmst_runbook == None:
pass
else:
return force_text(obj.jobmst_runbook[:-5])
How do I serialize django-mptt trees in Tastypie?
I want to use django-mptt's cache_tree_children(). I've tried applying in different Tastypie hooks, but it throws an error.
Without the cache_tree_children method you could probably have your children serialized by simply hooking up a ToManyField with full=True pointing at the children property:
class MenuResource(ModelResource):
children = fields.ToManyField('self', 'children', null=True, full=True)
parent = fields.ToOneField('self', 'parent', null=True)
class Meta:
queryset = Menu.objects.all()
To implement the cache_tree_children function you could write your own ToManyField subclass that overrides the standard dehydrate function. Please note, that I only tested this solution very superficially:
def dehydrate(self, bundle):
if not bundle.obj or not bundle.obj.pk:
if not self.null:
raise ApiFieldError("The model '%r' does not have a primary key and can not be used in a ToMany context." % bundle.obj)
return []
the_m2ms = None
previous_obj = bundle.obj
attr = self.attribute
if isinstance(self.attribute, basestring):
attrs = self.attribute.split('__')
the_m2ms = bundle.obj
for attr in attrs:
previous_obj = the_m2ms
try:
the_m2ms = getattr(the_m2ms, attr, None)
except ObjectDoesNotExist:
the_m2ms = None
if not the_m2ms:
break
elif callable(self.attribute):
the_m2ms = self.attribute(bundle)
if not the_m2ms:
if not self.null:
raise ApiFieldError("The model '%r' has an empty attribute '%s' and doesn't allow a null value." % (previous_obj, attr))
return []
self.m2m_resources = []
m2m_dehydrated = []
# There goes your ``cache_tree_children``
for m2m in cache_tree_children(the_m2ms.all()):
m2m_resource = self.get_related_resource(m2m)
m2m_bundle = Bundle(obj=m2m, request=bundle.request)
self.m2m_resources.append(m2m_resource)
m2m_dehydrated.append(self.dehydrate_related(m2m_bundle, m2m_resource))
return m2m_dehydrated
One of the main advantages of this method is that you don't have to care about detail / list view constraints / differences no more. You even can parameterize this aspect of your resource further down until you got some kind of default behavior that fits your needs. Field-based, that is. Which I think is cool.
This is how I solved it:
class MenuResource(ModelResource):
parent = fields.ForeignKey('self', 'parent', null=True)
class Meta:
serializer = PrettyJSONSerializer()
queryset = Menu.objects.all().select_related('parent')
include_resource_uri = False
fields = ['name']
def get_child_data(self, obj):
data = {
'id': obj.id,
'name': obj.name,
}
if not obj.is_leaf_node():
data['children'] = [self.get_child_data(child) \
for child in obj.get_children()]
return data
def get_list(self, request, **kwargs):
base_bundle = self.build_bundle(request=request)
objects = self.obj_get_list(bundle=base_bundle,
**self.remove_api_resource_names(kwargs))
sorted_objects = self.apply_sorting(objects, options=request.GET)
paginator = self._meta.paginator_class(
request.GET, sorted_objects,
resource_uri=self.get_resource_uri(), limit=self._meta.limit,
max_limit=self._meta.max_limit,
collection_name=self._meta.collection_name
)
to_be_serialized = paginator.page()
from mptt.templatetags.mptt_tags import cache_tree_children
objects = cache_tree_children(objects)
bundles = []
for obj in objects:
data = self.get_child_data(obj)
bundle = self.build_bundle(data=data, obj=obj, request=request)
bundles.append(self.full_dehydrate(bundle))
to_be_serialized[self._meta.collection_name] = bundles
to_be_serialized = self.alter_list_data_to_serialize(request,
to_be_serialized)
return self.create_response(request, to_be_serialized)
If you're not using pagination you can just take that part out. That's what I did.