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

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)

Related

Django dropdown filter queryset with FilterView

I want to filter apartments by selecting subcity field in a dropdown in my django app. I'm using django-filters and django-bootstrap-form. But the dropdown does not populate with database querysets. How can I make the dropdown work?
models.py:
from django.contrib.sites.models import Site
from django.contrib.gis.db import models
from django.utils.crypto import get_random_string
from django.contrib.gis.geos import GEOSGeometry,Point
from django.contrib.auth.models import AbstractUser
from django.shortcuts import render
from django.urls import reverse
from django.forms import ModelForm
from django.template.defaultfilters import slugify
import datetime
from leaflet.forms.widgets import LeafletWidget
from django.contrib.gis.db import models as geo_models
# Create your models here.
class User(AbstractUser):
pass
geos_pnt=Point(4314498.56, 1003834.600,srid=3857)
#pnt=GEOSGeometry('POINT(4314498.56, 1003834.600)').wkt
class Apartment(models.Model):
ADKT='Addis Ketema'
AKLT='Akaki-Kality'
ARDA= 'Arada'
BOLE='Bole'
GLLE='Gulele'
KLFE='Kolfe-Keranio'
KIRK='Kirkos'
LDTA='Lideta'
YEKA='Yeka'
NFSL='Nefas Silk-Lafto'
SUBCITY_CHOICES = [
(ADKT, 'Addis Ketema'),
(AKLT, 'Akaki-Kality'),
(ARDA, 'Arada'),
(BOLE, 'Bole'),
(GLLE, 'Gulele'),
(KLFE, 'Kolfe-Keranio'),
(KIRK,'Kirkos'),
(LDTA, 'Lideta'),
(NFSL, 'Nefas Silk-Lafto'),
(YEKA, 'Yeka')]
apt_id = models.CharField(max_length=200, primary_key=True,editable=True)
geom = geo_models.PointField(null=True)
apt_area = models.IntegerField(default=0, null=True)
no_bedrooms = models.IntegerField(null=True)
apt_cost = models.IntegerField(default=0, null=True)
apt_subcity = models.CharField(default='KIRK',choices=SUBCITY_CHOICES,max_length=30,null=True)
register_date = models.DateTimeField(auto_now_add=True,null=True)
objects = models.Manager()
sites =models.ManyToManyField(Site)
#change points from apt_rent_db to kml
def pointkml(self):
points = Apartment.objects.kml()
return render("placemarks.kml", {'places': points})
def get_absolute_url(self):
return reverse('rent_app:apartment-listing', kwargs={'pk': self.pk})
def save(self, *args, **kwargs):
#self.Latitude = self..y
#self.Longitude = self.location.x
self.slug = slugify(self.apt_id)
super(Apartment, self).save(*args, **kwargs)
class Meta:
# order of drop-down list items
verbose_name = ("Apartment")
verbose_name_plural = ("Apartments")
ordering = ('apt_cost',)
app_label = 'rent_app'
def __unicode__(self):
return self.apt_id
#property
def picture_url(self):
return self.picture.url
class UserProfile(models.Model):
first_name = models.CharField(max_length=100, null=False)
last_name = models.CharField(max_length=100,null=False)
gender = models.CharField(max_length=100)
phone_no = models.CharField(max_length=12)
sites = models.ManyToManyField(Site)
views.py:
class ApartmentFilterView(FilterView):
model = Apartment
context_object_name = 'apartments'
filter_class = ApartmentFilter
filters.py:
import django_filters
from .models import Apartment,UserProfile
class ApartmentFilter(django_filters.FilterSet):
ADKT = 'Addis Ketema'
AKLT = 'Akaki-Kality'
ARDA = 'Arada'
BOLE = 'Bole'
GLLE = 'Gulele'
KLFE = 'Kolfe-Keranio'
KIRK = 'Kirkos'
LDTA = 'Lideta'
YEKA = 'Yeka'
NFSL = 'Nefas Silk-Lafto'
SUBCITY_CHOICES = [
(ADKT, 'Addis Ketema'),
(AKLT, 'Akaki-Kality'),
(ARDA, 'Arada'),
(BOLE, 'Bole'),
(GLLE, 'Gulele'),
(KLFE, 'Kolfe-Keranio'),
(KIRK, 'Kirkos'),
(LDTA, 'Lideta'),
(NFSL, 'Nefas Silk-Lafto'),
(YEKA, 'Yeka')]
ordering = django_filters.ChoiceFilter(label='Ordering',subcity_choices=SUBCITY_CHOICES, method='filter_by_ordering')
class Meta:
model = Apartment
fields = {
'apt_cost': ['lte'],
#'apt_dist': ['lt'],
'apt_subcity': ['icontains'],
}
template:
{% extends 'base.html' %}
{% load bootstrap %}
{% block title %} የተገኙ ቤቶች | Apartment List {% endblock title %}
{% block content %}
<form action="" method="get">
{{ filter.form.as_p }}
<input type="submit">
</form>
{% for obj in filter.qs %}
{{obj.apt_id}} - Birr {{obj.apt_cost}}
{% endfor %}
{% endblock %}
Your model should be listed in the Meta class.
class yourfilter(django_filters.FilterSet):
class Meta:
model = your_model

Slugfield not working if field name is different from slug

Good evening, Django is completely new for me and it's my first question here.
I'm trying to create a Webapp. I'm using Django, Python and MariaDB.
I created a project with two apps and I have a model for each app. In the fist one I used "slug" as field name and everything is working fine. In the second one I wanted to differentiate that field giving a different name (bk_slug) defined as SlugField. I tried to use the same kind of instructions lines and modifying them for the field name it seems not working. I cannot have the right URL (Class based ListView) and cannot access to the Class based DetailView....
Thanks in advance for your support.
models.py
from django.db import models
from django.conf import settings
from django.utils import timezone
from django.urls import reverse
# book masterdata
class Book(models.Model):
bk_title = models.CharField("Book Title", max_length=100,
primary_key=True)
bk_originaltitle = models.CharField("Book original Title",
max_length=100, blank=True)
bk_author = models.CharField("Author", max_length=50)
bk_editor = models.CharField("Editor", max_length=50)
bk_editiondate = models.CharField("Book Edition date",
max_length=30)
bk_recblocked = models.BooleanField("Book record blocked")
bk_creator = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.PROTECT,
related_name='+', verbose_name="Created by")
bk_creationdate = models.DateTimeField("Creation date",
auto_now=True)
bk_modifier = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.PROTECT,
related_name='+', verbose_name="Last modification by")
bk_modified = models.DateTimeField("Last modification date",
auto_now=True)
bk_slug = models.SlugField(max_length=100, allow_unicode=True,
blank=True)
def __str__(self):
return self.bk_title
def get_absolute_url(self):
return reverse('book_detail', kwargs={'slug': self.bk_slug})
urls.py
from django.urls import path
from dimlibrary.views import BookListView
from dimlibrary.views import BookDetailView
urlpatterns = [
path('', BookListView.as_view(), name='book_list'),
path('<slug:bk_slug>/', BookDetailView.as_view(),
name='book_detail'),
]
views.py
from django.shortcuts import render
# Create your views here.
from django.shortcuts import render
from django.utils import timezone
from django.views.generic.list import ListView
from django.views.generic.detail import DetailView
from dimlibrary.models import Book
# book views :
# List view
class BookListView(ListView):
model = Book
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
# Details View
class BookDetailView(DetailView):
model = Book
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
```html
{% extends 'base/base.html' %}
{% load static %}
{% block content %}
<h1>Books List</h1>
<ul>
{% for book in object_list %}
<li><a href="{{ dimlibrary.book.get_absolute_url }}">{{
book.bk_title }}</a> - {{ book.bk_author }} -
{{ book.bk_editor }}</li>
{% empty %}
<li>No book registred yet.</li>
{% endfor %}
</ul>
{% endblock content %}
In your DetailView, you need to specify the slug_field [Django-doc] as 'bk_slug':
class BookDetailView(DetailView):
model = Book
slug_field = 'bk_slug'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
In the model, you will need to slugify(…) [Django-doc] the name, so:
from django.utils.text import slugify
class Book(models.Model):
# …
def save(self, *args, **kwargs):
if not self.bk_slug:
self.bk_slug = slugify(self.title)
return super().save(*args, **kwargs)

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

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
})

Can't create a custom auth model with "if user.is_authenicated" in html

Hi I am trying to make a register link in my html-file. But it only works when I am already logged in.
settings.py
AUTH_USER_MODEL = 'users.User'
models.py
from django.db import models
from django.contrib.auth.models import AbstractUser
from django.urls import reverse_lazy
class User(AbstractUser):
# Address
plz = models.CharField(max_length=5)
ort = models.CharField(max_length=30)
strasse = models.CharField(max_length=30)
strnr = models.CharField(max_length=5)
# Kontakt
mobil = models.CharField(max_length=20)
forms.py
I customized the original UserCreationForm to implement to additional fields:
class UserCreate(forms.ModelForm):
--snip--
class Meta:
model = User
fields = ('username', 'password1', 'password2', 'first_name',
'last_name', 'email', 'mobil', 'plz', 'ort',
'strasse', 'strnr',)
views.py
class UserCreate(CreateView):
model = User
form_class = UserCreate
template_url_suffix = '_create_form'
def get_context_data(self, **kwargs):
context = super(UserCreate, self).get_context_data(**kwargs)
context['head'] = 'Account erstellen'
return context
urls.py
url(r'^user/create/$', views.UserCreate.as_view(), name='user-create'),
If I am logged in, I can use the link to create a user instance:
base.html
<body>
<ul>
<li>Home</li>
<li>register</li>
{% if user.is_authenticated %}
<li>Account</li>
{% if user.sportler %}
<li>Sportler</li>
{% else %}
<li>Sportler werden</li>
{% endif %}
....
How can I make it work, if one is not logged in???
Error: Reverse for 'user-detail' with arguments '(None,)' not found. 1 pattern(s) tried: ['user/(?P[0-9]+)/detail/$']
I had a back-link in my creation form. Call me morron.
<button>Zurück</button>
Edited it to <button>Zurück</button> and it works...

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))