I am new to Django framework. This problem "profile matching query does not exist" comes and I don't understand where this problem is generating from. Please Let me know what else code is needed to resolve this error. I will update this question.
profile matching query does not exist
!["profile matching query does not exist"](https://i.stack.imgur.com/YfHio.png)
I have rechecked the code in urls.py, views.py, index file. But I could not resolve this.
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('',views.index, name = 'index'),
path('signup',views.signup, name = 'signup'),
path('signin',views.signin, name = 'signin'),
path('logout',views.logout, name = 'logout'),
path('settings',views.settings, name = 'settings'),
path('upload',views.upload, name = 'upload'),
]
views.py -> index
#login_required(login_url='signin')
def index(request):
user_object = User.objects.get(username=request.user.username)
user_profile = Profile.objects.get(user=user_object)
return render(request, 'index.html', {'user_profile':user_profile})
OK, so, it looks as though you don't have a Profile record associated with the User object.
def index(request):
user_object = User.objects.get(username=request.user.username)
user_profile = Profile.objects.get(user=user_object)
You need to check the value of user_object before looking for the profile, though pretty sure this is OK, then handle that Profile.objects.get if it doesn't actually find an associated Profile record.
You could do this by
try:
user_profile = Profile.objects.get(user=user_object)
except Profile.DoesNotExist:
... handle the error here
Alternatively, you could use the get_object_or_404 method, which would redirect you to your 404 page if it didn't find a record.
https://docs.djangoproject.com/en/4.1/topics/http/shortcuts/#get-object-or-404
Related
I am building a map with different station location.
The stations belong to different fields.
I have to show all station and, I have all station of a field.
At some point my api is called
"""Markers API URL Configuration."""
# Maps with Django (2)
# https://www.paulox.net/2021/07/19/maps-with-django-part-2-geodjango-postgis-and-leaflet/
from rest_framework import routers
from map.viewsets import MarkerViewSet
router = routers.DefaultRouter()
router.register(r"map", MarkerViewSet)
urlpatterns = router.urls
then the MarkerViewSet is called (viewsets.py)
class MarkerViewSet(viewsets.ReadOnlyModelViewSet):
"""Marker view set."""
#print(self.kwargs.get('idfield'))
bbox_filter_field = "location"
filter_backends = (filters.InBBoxFilter,)
queryset = Stations.objects.filter(station_active=1, map=1)
serializer_class = StationsSerializer
def get_queryset(self, **kwargs):
#field_id = self.kwargs['idfield']
#print("pp:", self.kwargs)
return Stations.objects.filter(fields_id_field=1)
The code above works, but it only show the markers of the field 1
If I change this to 2
return Stations.objects.filter(fields_id_field=2)
It show all station of the field with the id 2
My url is as the follwoing http://127.0.0.1:8080/map/ to print all stations of all fields.
If I want to have the stations of the field 1, my url will be
http://127.0.0.1:8080/map/1/field
and for the field 2 and 4
http://127.0.0.1:8080/map/2/field
http://127.0.0.1:8080/map/4/field
My problem, I can not not and I do not know of to get the id 1,2,4 or another form my url
this does not work
#field_id = self.kwargs['idfield']
#print("pp:", self.kwargs)
Here is my map/urls.py
an my project urls.py
Should I try to get the id of the field from the viewsets.py or how would you suggest me to archive my goal?
EDIT:
Here is my views.py. Here I can get idfield
Would it have a way to pass it my viewsets.py?
I beleive that your proposition only works in views.py as it start with
def field(request, idfield):
request.GET.get("idfield")
isn't?
I am working with a viewsets.py starting with
class MarkerViewSet(viewsets.ReadOnlyModelViewSet):
"""Marker view set."""
bbox_filter_field = "location"
filter_backends = (filters.InBBoxFilter,)
queryset = Stations.objects.filter(station_active=1, map=1)
serializer_class = StationsSerializer
"""
def get_tags(self):
return Stations.objects.filter(fields_id_field=1)
"""
def get_queryset(self):
#field_id = self.kwargs['idfield']
#print("ppp:", self.kwargs['idfield'])
return Stations.objects.filter(fields_id_field=1)
I do know where your proposition could be added.
However, I think I am getting close to the solution, but I still get error.
I hope you can help me
First, in my map.js file. I added
async function load_markers() {
const markers_url = `/api/map/1/`; // LOOK AT THIS LINE
console.log("markers_url: ",markers_url);
const response = await fetch(markers_url);
//console.log("response: ",response);
const geojson = await response.json();
console.log("geojson: ",geojson);
return geojson;
}
In my urls.py file, I changed to
path("api/<int:idf>/", include("map.api")),
which will redirect to the api.py file. I think, all is correct until this point, isn't?
In my api.py file, I have tried serveral things getting inspirated from the django-rest-framework - router page
router = routers.DefaultRouter()
#router.register(r"map", MarkerViewSet) #INITIAL
#router.register(r"^map/{idf}/$", MarkerViewSet) #I tried this
#router.register(r"^map/(?P<idf>[0-9]+)/$", MarkerViewSet) #this generate an error because of idf
router.register(r"^map/(?P<id_f>[0-9]+)/$", MarkerViewSet)
urlpatterns = router.urls
Another error message is on Firefox:
enter image description here
I believe, I should find the right format, but something else should be wrong
Many thanks for your help
Args
I believe you API urls should be as follows
/maps/ --> returns a list of objects
/maps/<id>/ --> returns a single object
If you do this you should be able to get results according to the given id (if primary key) without doing anything in your view. viewsets automatically returns an object based on the lookup field. If it is not a primary key you can set different lookup field.
Kwargs
in kwargs your URL should be as /maps/?idfield=<id>, then you will be able to do the followings.
kwargs from GET request can be obtained as below
request.GET.get("idfield")
Views.py
def Login(request):
if request.method == 'POST':
username = request.POST.get('username')
password = request.POST.get('password')
user = authenticate(request , username=username , password=password)
if user is not None:
try:
is_teacher= Teacher.objects.get(profile_id=user.id)
except Teacher.DoesNotExist:
is_teacher = None
if is_teacher is not None:
login(request , user)
is_teacher= Teacher.objects.get(profile_id=user.id)
return redirect('teacher_dashboard' , {'teacher' : is_teacher})
else:
login(request , user)
return redirect('student_dashboard' )
return render (request , "pages/login.html")
urls.py
path('teacher_dashboard/', views.TeacherDashboard , name='teacher_dashboard'),
path('student_dashboard/', views.StudentDashboard , name='student_dashboard'),
I want to send queryset with a html page when its redireted
there are 2 errors in your code
return redirect('teacher_dashboard' , {'teacher' : is_teacher})
since the url doesnt have any parameters
path('teacher_dashboard/', views.TeacherDashboard , name='teacher_dashboard'),
you need
return redirect('teacher_dashboard')
if you want to redirect to individual teachers dashboard
return redirect('teacher_dashboard' , {'teacher' : is_teacher.id})
and url will be
path('teacher_dashboard/<int:teacher>', views.TeacherDashboard , name='teacher_dashboard')
In your urls.py the path is like this:
path('teacher_dashboard/', views.TeacherDashboard , name='teacher_dashboard')
Here 'teacher_dashboard/' does not expect anything after the '/'. If you need to pass any parameters then you should make that part of the path specified in urls.py
However, this is not possible. Whatever you need to pass with URL practically comes from browsers and you do not expect the browser to pass a queryset. So bascially what you can do is pass pk of the teacher object in the URL and then get the object in TeachDashboard again
Your URL doesn't accept any arguments. You need to allow the URL to include the data you'll use in the view;
urlpatterns = [
path("teacher_dashboard/<int:teacher>/", views.TeacherDashboard, name="teacher_dashboard")
The docs for URL paths is here with a good example detailing date based URLs.
You also want to pass just the Teacher ID, not the whole object. So your view should do;
is_teacher = Teacher.objects.get(profile_id=user.id).id
return redirect('teacher_dashboard' , {'teacher' : is_teacher})
On an additional point of the code, if I saw a variable called is_teacher I'd expect a bool because it either is or isn't a teacher. Therefore I'd suggest you also change that to teacher = Teacher.objects.get(profile_id=user.id) because you are getting a teacher object from the database.
I am developing a webapp using django. Generally, I want to keep track of how much time a user has devoted to a project. So when the user starts working, I am registering a "Change" object in the database with the user, the project, and what time he start working. Now, how can I get the same "Change" object to a different view to log the end time? In my best attempt I got an "IntegrityError NOT NULL constraint failed". Here is the code:
views.py
#login_required
def main(request):
context = RequestContext(request)
user=request.user
if request.method=='POST':
projectid=request.POST['project']
project = Project.objects.get(pk=int(projectid))
if project:
change=Change(user=user, project=project,starttime=datetime.now())
change.save()
#return HttpResponse("I \'ve already start counting... You \'ve wasted 5 seconds already. Just joking. I don\'t know how to count...")
return render_to_response('ProjectLogging/timer.html', {'change':change}, context_instance=RequestContext(request))
else:
HttpResponse("Choose a valid project!")
else:
HttpResponse("Choose a POST method (???????)")
#login_required
def timer(request, change):
user=request.user
# schange=request.change
if request.method=='POST':
change=Change(endtime=datetime.now())
change.save()
return render_to_response('ProjectLogging/main.html',{'user':user, 'project_list':Project.objects.all()}, context_instance=RequestContext(request))
else:
return HttpResponse("Something went wrong with timer view.")
urls.py
urlpatterns=patterns('ProjectLogging',
url(r'^$', 'views.login', name="index"),
url(r'^login/$', 'views.login', name="login"),
url(r'^logout/$', 'views.logout', name="logout"),
url(r'^main/$','views.main', name="main"),
url(r'^timer/$', 'views.timer', {'change':'change'}),
)
and the Change model
class Change(models.Model):
user=models.ForeignKey(User)
project=models.ForeignKey('Project')
starttime=models.DateTimeField(null=True,blank=True)
endtime=models.DateTimeField(null=True, blank=True)
flagged=models.BooleanField(default=False, db_index=True)
def __repr__(self):
return ('Change in project %r from %r' % (self.project.title, self.user.username))
def __unicode__(self):
return ('%r in project: %r' % (self.user.get_full_name(), self.project.title))
def user_changes(self, user):
return self.filter(user==user)
Sorry for the primitive code. I m new to both Django and Python.
the error is here:
change=Change(endtime=datetime.now())
change.save()
You are trying to create a new object...
Instead you need to get the previous created one and save it.
you need to pass the id to the post , get the object and save it again:
change = Change.objects.get(id=change_id)
change.endtime=datetime.now()
change.save()
This is what I would do:
change the url from this
url(r'^timer/$', 'views.timer', {'change':'change'}),
to this:
url(r'^timer/$', 'views.timer', name='timer'),
Pass the change_id in the form as a hidden input. Since you're not using django Forms, you'll have to write this
<input type="hidden" value="{{ change.id }}" name="change_id" />
Change the timer function to this:
#login_required
def timer(request):
...
if request.method=='POST':
try:
change = Change.objects.get(id=request.POST.get('change_id'))
change.endtime=datetime.now()
change.save()
except:
...
that should be ok
As simple as this is, I'm having trouble getting the value of a GET parameter d
I'm clicking on a link like:
http://127.0.0.1:8000/Account/Site/d=mysite.com
The view that, that url serves is:
#login_required
def Site(request):
if request.user.is_authenticated():
# verify domain in url is associated with authenticated users account
DomainToScan = request.GET.get('d')
VerifyDomainAgainstDb = Tld.objects.filter(FKtoClient=request.user,domainNm=DomainToScan)
else:
HttpResponseRedirect("/Login/")
return render(request, 'VA/account/begin_site.html', {
'Site':Site,
'VerifyDomainAgainstDb':VerifyDomainAgainstDb
})
specifically, this line:
DomainToScan = request.GET.get('d')
the value of DomainToScan is outputting as None when viewing the django template begin_site.html
What am I doing wrong here?
Thank you!
UPDATE:
urls.py
(r'^Account/Site/[?]d=[A-za-z0-9]{2,50}.[a-z]{1,3}$', Site),
For some reason this isn't matching a url like:
http://127.0.0.1:8000/Account/Site/?d=mysite.com
Any reason why? Rubular says its valid
You don't have any GET parameters. If you want domain to be a GET parameter, your link should be http://127.0.0.1:8000/Account/Site/?d=mysite.com - notice the ?.
(Also note you would need to actually return HttpResponseRedirect(), not just call it: but the whole checking of is_authenticated is pointless anyway because the function is decorated with login_required, so a non-authenticated user wouldn't even get into that view.)
Try:
#login_required
def Site(request, DomainToScan=None):
if request.user.is_authenticated():
# verify domain in url is associated with authenticated users account
VerifyDomainAgainstDb = Tld.objects.filter(FKtoClient=request.user,domainNm=DomainToScan)
else:
return HttpResponseRedirect("/Login/")
return render(request, 'VA/account/begin_site.html', locals())
urls.py
(r'^Account/Site/(?P<DomainToScan>[^/]+)/', Site),
When I try to submit, I get a TypeError:
int() argument must be a string or a number, not 'SimpleLazyObject'
My views.py:
def bookmark_save_page(request):
if request.method == 'POST':
form = BookmarkSaveForm(request.POST)
if form.is_valid():
# Create or get link.
link, dummy = Link.objects.get_or_create(
url=form.cleaned_data['url']
)
# Create or get bookmarks.
bookmark, created = Bookmark.objects.get_or_create(
user = request.user,
link = link
)
# Update bookmark title.
bookmark.title = form.cleaned_data['title']
# If the bookmark is being updated, clear old tag list.
if not created:
bookmark.tag_set.clear()
# Create new tag list.
tag_names = form.cleaned_data['tags'].split()
for tag_name in tag_names:
tag, dummy = Tag.objects.get_or_create(name=tag_name)
bookmark.tag_set.add(tag)
# Save bookmark to database.
bookmark.save()
return HttpResponseRedirect(
'/user/%s/' %request.user.username
)
else:
form = BookmarkSaveForm()
variables = RequestContext(request, {'form': form})
return render_to_response('bookmark_save.html',variables)
Please guide me.
Thank you.
request.user, by default is of type SimpleLazyObject. To resolve it,
bookmark, created = Bookmark.objects.get_or_create(
user = request.user,
link = link
)
should be
bookmark, created = Bookmark.objects.get_or_create(
user = request.user.id,
link = link
)
If this does not resolve it, make sure you are logged in.
There is another option, may be this solution will help you fix it.
from django.contrib import auth
bookmark, created = Bookmark.objects.get_or_create(
user = auth.get_user(request),
link = link
)