How to display twitter feeds based on users in django & tweepy? - django

I want to show twitter data based on twitter username in my
template (Tweepy) but I don't know how to send data from my models into my views.
The content of models.py is:
<pre>
from django.db import models
from django.conf import settings
User = settings.AUTH_USER_MODEL
# Create your models here.
class Feed(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
feed = models.CharField(max_length=211, blank=True, null=True)
twitter = models.CharField(max_length=211, blank=True, null=True) # this is the twitter username which the user can enter and be sent to the views to api.get_user(twitter)
def __str__(self):
return self.feed
</pre>
The content of views.py is:
<pre>
from django.shortcuts import render
from django.views.generic import TemplateView
from .tweet import *
from .models import Feed
def feed(request):
api = tweepyapi(request)
user = api.get_user(twitter) # I want this portion to be dynamic.
findfriends = user.friends()
return render(request, 'feeds/feeds.html', {
'user': user,
'findfriends': findfriends
})
</pre>

let's say you have Profile model related to User model via one-to-one relation
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
twitter_username = models.CharField(max_length=40, blank=True)
def get_absolute_url(self):
context = {
'id':self.id,
}
return reverse("viewprofile", kwargs=context)
and in your template, we provide a link to user's profile as
{% for user in user_list %}
{{ user.get_full_name }}
{% endfor %}
now assuming you are passing id of user in get_absolute_url, your url will look like
url(r'^(?P<id>[0-9]+)/$', views.feed, name="viewprofile")
and then in your view
def feed(request,id):
profile = get_object_or_404(UserProfile,user__id=id )
api = tweepyapi(request)
user = api.get_user(profile.twitter_username)
findfriends = user.friends()
return render(request, 'feeds/feeds.html', {
'user': user,
'findfriends': findfriends
})

Related

how can show profile User in html django

i create user auth and make model profile user with signals to create profile like User
but i want show user profile in template
---- model
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
music = models.CharField(max_length=50)
skils = models.CharField(max_length=50)
search = models.CharField(max_length=50)
posts = models.CharField(max_length=50)
boi = models.TextField()
img = models.ImageField(upload_to="profile-img")
def __str__(self):
#return self.user or 'User'
return str(self.id)
def create_profile(sender, **kwargs):
if kwargs['created']:
user_profile = profile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender=User)
---- path
path('profile/<int:id>', views.profile, name="profile")
----- views
def profile(request, id):
ff = profile.objects.get(id=id)
context = {'ff' : ff}
return render(request, 'profile.html', context)
views not work i dont know the problem
in html...
{% url 'profile' profile.id %}
how can show profile User in html django
If you want User can show his Profile, you need to get the Profile object using the current user instance instead of profile id like this...
views.py
def profile(request):
ff = profile.objects.get(user=request.user) # This query object give logged in user profile
context = {'ff' : ff}
return render(request, 'profile.html', context)
Profile url path become like this
urls.py
path('profile/', views.profile, name="profile")
Html url becomes like this
{% url 'profile' %}
NOTE - No need pass id of profile because here we get profile of current user which is logged in

cannot accès to my Model Data base from views.py

I m learning Django 2.2, I am trying to a model from named sKills base on a parent model named Profile:
But I have this error :
DoesNotExist at /skills/
Profile matching query does not exist.
Request Method: GET
Request URL: http://127.0.0.1:8080/skills/
Django Version: 2.2
Exception Type: DoesNotExist
Exception Value:
Profile matching query does not exist.
in Skills => models.py:
from django.db import models
from profiles.models import Profile
from django.core.validators import MaxValueValidator, MinValueValidator
# Create your models here.
class Skill(models.Model):
user = models.ForeignKey(Profile, on_delete=models.CASCADE)
name = models.CharField(max_length=220)
score = models.PositiveIntegerField(
validators=[MinValueValidator(1), MaxValueValidator(5)])
def __str__(self):
return "{}-{}-{}".format(self.user, self.name, self.score)
in Skills => Views.py:
# Create your views here.
def skill_view(request):
user_id = request.user.id
profile = Profile.objects.get(pk=user_id)
#profile = get_object_or_404(Profile, pk=user_id)
SkillFormset = inlineformset_factory(Profile, Skill,fields='__all__',extra=1)
formset = SkillFormset( instance=profile)
context = {
'formset': formset
}
return render(request,'skills/add.html',context)
In Skills => urls.py:
app_name = 'skills'
urlpatterns = [
path('', skill_view, name='my-skills'),
]
In Skills => templates =>skills => add.html:
{% extends 'base.html' %}
{% block title %}my skills{% endblock title %}
{% block content %}
<form action="" method="POST">
{{formset}}
</form>
{% endblock content %}
In Profile => Models:
from django.db import models
from django.contrib.auth.models import User
from django.core.validators import FileExtensionValidator
# Create your models here.
class Profile(models.Model):
name = models.ForeignKey(User, on_delete=models.CASCADE)
website = models.URLField(blank=True)
avatar = models.ImageField(upload_to='uploads/img', validators=[FileExtensionValidator(allowed_extensions=['png'])], blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
#property
def get_created(self):
return self.created.strftime("%m/%d/%Y, %H:%M:%S")
def __str__(self):
return "{}-{}".format(self.name, self.get_created)
I have Profile user in database I do not understand:
Thanks for your help
As you are looking up on pk against User id which is not right as you don't have made the name field as primary_key=True or inherited from User model itself. You have to look up on name field of profile
profile = Profile.objects.get(name_id=user_id)
You can set name as primary key like this:
name = models.ForeignKey(User, on_delete=models.CASCADE, primary_key=True)
and then you can look up on pk:
profile = Profile.objects.get(pk=user_id)

'QuerySet' object has no attribute

Please could you me why I get this error message while displaying "fav" in my template
QuerySet object has no attribute game_id
I tried to replace game_id by game, id_game but nothing...
view.py
from django.contrib import messages
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.shortcuts import render
from start.models import Games, FavoriteGames
import urllib, json
def view_recap(request):
if request.user.is_authenticated():
username = request.user.username
id_user = request.user.id
fav = FavoriteGames.objects.filter(user_id=id_user).game_id
return render(request, 'recap.html', locals())
else:
from start.views import view_logoff
from start.views import view_logon
messages.add_message(request, messages.INFO, 'Vous devez être connecté pour accéder à cette page.')
return redirect(view_logon)
models.py
from django.db import models
from django.conf import settings
# Create your models here.
class Games(models.Model):
guid = models.CharField(max_length=100, unique=True, null=False, verbose_name="GUID")
title = models.CharField(max_length=100, null=False, verbose_name="Titre")
logo = models.CharField(max_length=100, null=True, blank=True, verbose_name="Logo")
date = models.DateTimeField(auto_now_add=True, auto_now=False, verbose_name="Date de création")
update = models.DateTimeField(auto_now=True, verbose_name="Dernière modification")
def __str__(self):
return self.title
class FavoriteGames(models.Model):
game = models.ForeignKey('Games')
user = models.ForeignKey(settings.AUTH_USER_MODEL)
When you loop through the queryset you can access the game_id for each instance. You can't access it on the queryset.
You can loop through the queryset in the view,
favs = FavoriteGames.objects.filter(user_id=id_user)
for fav in favs:
game_id = game_id
or in the template:
{% for fav in favs %}
{{ fav.game_id }}
{% endfor %}
If you only need the game_ids from the queryset, you could use values_list:
game_ids = FavoriteGames.objects.filter(user_id=id_user).values_list('game_id', flat=True)
filter will return Queryset.So use get instead of filter. If multiple objects are there use filter, but you need to loop over that queryset to get each objects.

Django: text-input instead selection on foreignkey

I want to create a messaging function in ma django app. User should be able to write other users a textmessage.
models.py
from django.contrib.auth.models import User
class Message(models.Model):
recipient = models.ForeignKey(User, null=True)
contentDescription = models.CharField(max_length=1000, null=True)
By default, with no forms.py entry I get a selection, which will be unuseful with many users. I want the message sender to type in the user name, or in the first step the user id (which I could resolve with ajax from the name) .
Integer
But with forms.py
recipient = forms.IntegerField( widget=forms.NumberInput , required=False,)
I get:
Cannot assign "11": "Transport.recipient" must be a "User" instance.
ChoiceField and NumberInput
with:
recipient = forms.ChoiceField( widget=forms.NumberInput, required=False,)
I get the error message "not valid"
Is it possible to write the foreignkey 'manually' at all?
Try this:
recipient = forms.ModelChoiceField(queryset=User.objects.all(), widget=forms.Select, required=False)
considering your
models.py -
from django.contrib.auth.models import User
class Message(models.Model):
recipient = models.ManytoMany(User, null=True)
contentDescription = models.TextField()
forms.py
from .models import Message
from django import forms
from django.contrib.auth.models import User
class MailForm(forms.ModelForm):
recipient = forms.Charfield()
class Meta:
model = Message
fields = ('contentDescription',)
def clean_recipient(self):
user_list = self.cleaned_data.get('recipient')
# considering you post user_list of usernames as 'username1,username2,username3'
if user_list is not None:
user_list = user_list.split(',')
user_qs = User.objects.filter(username__in=userlist)
else:
raise forms.ValidationError('Error in this field')
return user_qs
def save(self, user_qs):
self.instance.user = user_qs
return super().save()
in views.py -
from .forms import MailForm
def your_view(request):
form = MailForm(request.POST or None)
if form.is_valid():
user_qs=form.cleaned_data.get('recipient')
form.save(user_qs)
#return render here
else:
#create your context here and return render
This is not perfect but can give you an idea how to implement. With the details you gave this is the best I can do for now.

How to do custom signup with django-allauth?

I'm trying to ask a user some additional info while signing up. I'm using django allauth for authorization and authentication. I try to add three more fields during the signup process. If If I run it, it shows me the standard form plus gender field. However, it doesn't seem to really work. How can I save the data? Could someone help? Thank you in advance!
EDITED: if I just use
if form.is_valid():
form.save()
return redirect('/success/')
I get an error:
save() missing 1 required positional argument: 'user'
I'm quite new to django.
I created signups app in the project.
I put this in allauth_settings.py:
ACCOUNT_SIGNUP_FORM_CLASS = 'signups.forms.MySignupForm'
My signups/model.py:
from django.contrib.auth.models import User
from django.db import models
from allauth.account.models import EmailAddress
from allauth.socialaccount.models import SocialAccount
import hashlib
class UserProfile(models.Model):
user = models.OneToOneField(User, related_name='profile')
about_me = models.TextField(null=True, blank=True)
timestamp = models.DateTimeField(auto_now_add= True, auto_now=False)
updated = models.DateTimeField(auto_now_add= False, auto_now=True)
GENDER_CHOICES = (
('m', 'Male'),
('f', 'Female'),
)
# gender can take only one of the GENDER_CHOICES options
gender = models.CharField(max_length=1, choices=GENDER_CHOICES,
verbose_name='Gender')
def __unicode__(self):
return self.user.username
class Meta:
db_table = 'user_profile'
def profile_image_url(self):
"""
Return the URL for the user's Facebook icon if the user is logged in via
Facebook, otherwise return the user's Gravatar URL
"""
fb_uid = SocialAccount.objects.filter(user_id=self.user.id, provider='facebook')
if len(fb_uid):
return "http://graph.facebook.com/{}/picture?width=40&height=40".format(fb_uid[0].uid)
return "http://www.gravatar.com/avatar/{}?s=40".format(hashlib.md5(self.user.email).hexdigest())
def account_verified(self):
"""
If the user is logged in and has verified hisser email address, return True,
otherwise return False
"""
if self.user.is_authenticated:
result = EmailAddress.objects.filter(email=self.user.email)
if len(result):
return result[0].verified
return False
User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
my signups/forms.py:
from allauth.account.forms import SignupForm
from django import forms
from .models import UserProfile
class MySignupForm(SignupForm):
class Meta:
model = UserProfile
gender = forms.CharField(max_length=1, label='gender')
def save(self, user):
user.gender = self.cleaned_data['gender']
user.save()
my signups/views.py:
from django.template import RequestContext
from django.shortcuts import render_to_response
from .forms import SignupForm
def index(request):
form = MySignupForm(request.POST or None)
if form.is_valid:
???
return render_to_response("signups/index.html", locals(),
context_instance=RequestContext(request))
My index.html is very basic, I just wanted to see the representation of the form:
{% extends 'account/base.html' %}
{% block head_title %}ProjectName{% endblock %}
{% block content %}
<form method="POST" action="">
{{ form.as_p }}
<input type="submit">
</form>
{% endblock %}
You are instantiating the SignupForm, which is the standard form but not your MySignupForm in the view. Change it like this:
def index(request):
form = MySignupForm()
return render_to_response("signups/index.html", locals(),
context_instance=RequestContext(request))