Cannot get data of logged in User in Django - python

Respect for everyone here.
I have CustomUser model from one app, and Field model from another app. And I put a connection in CustomUser model with Field model via ManyToMany.
Field is for interested fields, and in signup form I have input like "In What do you have interests?"
I can easily get other datas like username, date_of_birth, email... But cannot get this interests. It returns courses.Field.None
Here is the models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from courses.models import Field
class CustomUser(AbstractUser):
username = models.CharField(max_length=32 , verbose_name="Login", unique=True, )
first_name = models.CharField(max_length=64, verbose_name="Ismingiz", blank=False, null=False)
second_name = models.CharField(max_length=64, verbose_name="Familyangiz", blank=False, null=False)
# & dob = date of birth
dob = models.DateField(auto_now_add=False, verbose_name="Yoshingiz", blank=False, null=True)
gender_choices = [("e", "Erkak"), ("a", "Ayol")]
gender = models.CharField(choices=gender_choices, verbose_name="Jinsingiz", default="e", max_length=1)
-> interests = models.ManyToManyField(Field, verbose_name="Qiziqishlaringiz")
longitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (uzunlik)", null=True, blank=True)
latitude = models.CharField(max_length=256, verbose_name="Yashash joyingiz (kenglik)", null=True, blank=True)
And this is my views.py file from courses App
from django.shortcuts import render
from .models import Center
from .serializers import CenterSerializer, UserSerializer
from rest_framework import generics
from django.contrib.auth import get_user_model
from rest_framework.response import Response
from decimal import Decimal
from slugify import slugify
import operator
from rest_framework.decorators import api_view
...
other views here
...
def center_list(request):
if request.method == 'GET':
dorilar = Center.objects.all()
serializers = CenterSerializer(dorilar, many=True)
dorixonalar = []
uzunlik = request.GET.get('uz')
kenglik = request.GET.get('keng')
------> print(request.user.interests)
interests = request.GET.get('interest').split(",")
if uzunlik and kenglik:
uzunlik = Decimal(uzunlik)
kenglik = Decimal(kenglik)
location = Decimal(uzunlik + kenglik)
dorixonalar = yaqinlik_boyicha_filter(dorilar, location, interests)
serializers = CenterSerializer(dorixonalar, many=True)
return Response(serializers.data)
else:
return Response(serializers.data)
Thanks in advance. :)

request.user.interests is a Manager. You need to:
print(request.user.interests.all())

Related

Filter_horizontal not save django admin 4x

I'm starting a project in django 4.1. and I run into this problem:
many to many relationship: I have a field of this type that is required, and everything is fine, but when I use the filter_horizontal it does not let me insert the chosen value, it tells me that it is required, however I am selecting values
Admin.py:
from django.contrib import admin
from .models import *
from django.contrib.auth.models import User
class CatalejoAdmin(admin.ModelAdmin):
filter_horizontal = ('tematicas',)
admin.site.register(Catalejo, CatalejoAdmin)
admin.site.register(Tematicas)
Model:
from django.db import models
from django.contrib.auth.models import User
class Tematicas(models.Model):
tematica = models.CharField(max_length=500)
fecha = models.DateTimeField(auto_now_add=True)
author = models.ForeignKey(User,null=True , default=User, editable=False, on_delete=models.DO_NOTHING)
class Meta:
ordering = ["tematica"]
verbose_name_plural = "Temática"
def __str__(self):
return self.tematica
class Catalejo(models.Model):
fecha = models.DateField()
titulo = models.CharField(max_length=500)
tematicas = models.ManyToManyField(Tematicas, related_name='Temáticas')
author = models.ForeignKey(User,null=True , default=User, editable=False, on_delete=models.DO_NOTHING)
fichero = models.FileField(upload_to='gestores/%Y/%m/%d', null=True, blank=True)
class Meta:
ordering = ["fecha"]
verbose_name_plural = "Catalejo"
def Tematicas(self):
return ",\n".join([p.tematica for p in self.tematicas.all()])
def dehydrate_full_title(self, Tematicas):
return '%s by %s' % (Tematicas.tematica)
enter image description here

serializer.data not showing any data

I'm still getting to know DRF but when I run the command serializer.data it returns an empty set. Here is what I'm working with
models.py
import datetime
from django.db import models
from django.db.models.fields.related import ForeignKey
from django.utils import timezone
from accounts.models import CustomUser
class IndustriaCategoria(models.Model):
name = models.CharField(max_length=20, null=False, blank=False)
def __str__(self):
return self.name
class Post(models.Model):
category = models.ForeignKey(IndustriaCategoria, on_delete=models.CASCADE)
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE)
title = models.CharField(max_length=512, null=False, blank=False)
body = models.TextField()
timestamp = models.DateTimeField(default=timezone.now)
link = models.URLField(max_length=500, null=True)
ups = models.IntegerField(default=0)
score = models.IntegerField(default=0)
hotness = models.IntegerField(default=0)
serializers.py
from django.db.models import fields
from rest_framework import serializers
from .models import IndustriaCategoria, Empresa, Post, Comment
class IndustriaCategoria(serializers.Serializer):
class Meta:
model = IndustriaCategoria
fielst = ('__all__')
class PostSerializer(serializers.Serializer):
class Meta:
model = Post
fields = ('__all__')
I have a management command which creates some data so I can just start throwing commands. Here is where the problem comes up:
>>> from accounts.models import CustomUser
>>> from forum.models import IndustriaCategoria, Post
>>> from forum.serializers import PostSerializer, IndustriaCategoria
>>> u = CustomUser.objects.all().first()
>>> i = IndustriaCategoria.objects.all().first()
>>> post = Post(category=i, author=u, title='hello world', body='this is a test', link='https://helloworld.com')
>>> post.save()
>>> serializer = PostSerializer(post)
>>> serializer.data
{}
Any idea why I got an empty set instead of the serialized data with the proportionated data when created the Post object?
Try to inherit from ModelSerializer instead of Serializer
class IndustriCategoria(serializers.ModelSerializer):
class Meta:
model = IndustriaCategoria
fielst = ('__all__')

How to return username instead of user object in DRF?

I want to set a username for each object. Here is my models.py
from django.contrib.auth.models import User
from django.conf import settings
# Tweet Model
class TweetModel(models.Model):
text = models.TextField(max_length=300, blank=False)
created_at = models.DateTimeField(auto_now_add=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True)
username = models.CharField(max_length=100, blank=True)
And viewset.py
from .models import TweetModel
from rest_framework import viewsets, permissions
# TweetViewset
class TweetViewset(viewsets.ModelViewSet):
permission_classes = [
permissions.IsAuthenticated
]
serializer_class = TweetSerializer
def get_queryset(self):
ordered = TweetModel.objects.order_by('-created_at')
return ordered
def perform_create(self, serializer):
serializer.save(owner=self.request.user, username=self.request.user.username)
But it is not working. Error is
django.db.utils.ProgrammingError: column tweets_tweetmodel.username does not exist
LINE 1: ...el"."created_at", "tweets_tweetmodel"."owner_id", "tweets_tw...
Can you help, please?
I forgot to run makemigrations and migrate

I am facing mapping user and profile in django

I am facing a problem with Django profile mapping with user.There is coming None in admin view
This is my models.py
profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
session = models.CharField(max_length=20, blank=False, null=False )
batch = models.IntegerField() # batch = models.IntegerField(blank=False, null=False)
iit_program = models.CharField(blank=True, choices=IIT_PROGRAM, max_length=10)
college = models.CharField(max_length=50)
graduate_university = models.CharField(max_length=50, default='Dhaka University')
graduate_department = models.CharField(max_length=50, default='Software Engineering')
photo = models.ImageField(blank=True)
is_current = models.BooleanField(default=True)
This is my views.py
from django.shortcuts import render
from .forms import UserProfile
from django.contrib.auth.decorators import login_required
#login_required(login_url= '/accounts/login/')
def userProfileview(request):
form = UserProfile(request.POST or None)
if form.is_valid():
form.save()
context = {'form':form}
return render(request,'userprofile.html', context)
This is my forms.py
from django import forms
from .models import Profile
class UserProfile(forms.ModelForm):
class Meta:
model = Profile
fields =
['iit_program','batch','session','graduate_university','graduate_department','photo']
What you see in the admin list view is the Model converted to a string, you can control how the model is converted with the str function, the return value of this function must be a string
class Profile(models.Model):
profile_of = models.OneToOneField(settings.AUTH_USER_MODEL, null=True, on_delete=models.CASCADE)
...
def __str__(self):
return self.profile_of.name

Django limit next inlinefield to first inlinefield

I have this model in django
from django.db import models
class ProductType(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
def __unicode__(self):
return self.name
class Product(models.Model):
name = models.CharField(max_length=250)
slug = models.SlugField(unique=True)
type = models.ForeignKey(ProductType, related_name='product_type')
related_products = models.ManyToManyField('self',blank=True,null=True)
description = models.TextField()
def __unicode__(self):
return self.name
What I would like to do is in the admin have the Products as tabular inline to a quote page that have multiple products. This thing is that the first selected model can be a parent to the others and therefore I would like the choices of the next elements to be sorted by the first.
this is the quote model
from django.db import models
from django.utils.translation import ugettext as _
import datetime
from products.models import Product
from customers.models import Customer
class Quote(models.Model):
quoteid = models.IntegerField(_('Quote ID'), max_length=8, unique=True, default=number)
slug = models.SlugField(unique=True,default=number)
add_date = models.DateTimeField(auto_now_add=True)
customer = models.ForeignKey(Customer, related_name='quote_customer',blank = True, null = True)
product = models.ManyToManyField(Product, related_name='quote_product')
def __unicode__(self):
return str(self.quoteid)
and the admin part
from django.contrib import admin
from quotes.models import Quote
class ProductInline(admin.TabularInline):
model = Quote.product.through
extra = 3
class QuoteAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('quoteid',)}
fieldsets = (
(('Quote'), {'fields': ('slug','quoteid','customer',)}),
)
list_display = ('quoteid','customer','add_date',)
inlines = [ ProductInline]
admin.site.register(Quote,QuoteAdmin)
I know this is quite tricky and I have tried many ways but I have not found a solution that works. I have tried with formfield_for_manytomany but I can't fully grasp how to return the first tabularinline object as the input for the queryset.
If someone have a link that explains a method to do this I would be grateful.

Categories

Resources