Exception happened during processing of request from ('127.0.0.1', 9464) - python

I don't know why this eror I wrote it from a tutorial but It's happend
this is view.py file
here
import view as view
from django.shortcuts import render
from django.http import HttpResponse
from django.views import View
# Create your views here.
from teams.models import Team
class HomePageView(View):
def get(self,requests):
all_teams = Team.objects.all()
context = {"teams": all_teams}
return render(requests,"teamlist.html",context)
this is my admin.py file
this is my admin.py file:here
from django.contrib import admin
# Register your models here.
from teams.models import Team, Player, GameScore
admin.site.register(Team)
admin.site.register(Player)
admin.site.register(GameScore)
that's my first question on stack over flow I don't know I ask True or not . I just need some help :)

Related

What is the best, cleanest and shortest way to check if a given value is valid URL when working with models?

I rather want to use Django's built-in functionalities as much as possible and avoid implementing stuff myself as much as possible!
Why doesn't the following code issue exceptions when given a non-URL value?
models.py:
from django.core.validators import URLValidator
from django.db import models
class Snapshot(models.Model):
url = models.URLField(validators=[URLValidator])
views.py:
from django.http import HttpResponse
from .models import Snapshot
def index(request):
a = Snapshot(url='gott ist tot')
a.save()
Because this validator is run when you use a django form.
More information about validators on the doc : https://docs.djangoproject.com/en/4.1/ref/validators/
if you do a form :
from django import forms
from .models import Snapshot
class SnshotForm(forms.ModelForm):
class Meta:
model = Snapshot
fields = ('url', )
and your views.py :
from django.http import HttpResponse
from .forms import SnapshotForm
def index(request):
a = SnapshotForm(data={'url': 'gott ist tot'})
if a .is_valid()
a.save()
else:
print(a.errors)
Your validator will be run and you will see the errors form message
Without using form, you can call manually validator in your view or in the save method:
# in views
from django.core.validators import URLValidator
from django.core.exceptions import ValidationError
def index(request):
url_validator = URLValidator()
url = 'gott ist tot'
is_valid_url = False
try:
url_validator(url)
except ValidationError:
pass
if is_valid_url:
a = Snapshot(url=url)
a.save()
else:
print(a.errors)
Be careful ! I do not recommanded to bypass the validator with forms, i think it is the better way for maximizing usage of django builtins funtions

ImportError: cannot import name 'forms' from 'basicapp'

form.py:
from django import forms
class FormName(forms.Form):
name=forms.CharField()
email=forms.EmailField()
text=forms.CharField(widget=forms.Textarea)
views.py:
from django.shortcuts import render
from .forms import forms
def index(request):
return render(request,'basicapp/index.html')
def form_page(request):
Form = forms.FormName()
return render(request,'basicapp/form_page.html',{'form':Form})
I dont know what is wrong here! when I run server, it makes an error, saying ImportError : cannot import name 'forms' from 'basicapp'.
First of all, it looks like you have named your forms file, form.py and you are trying to access a module called forms. Rename form.py file to forms.py.
Second, you are trying to import forms from your forms file. This is actually referencing forms you imported via from django import forms. You have a couple options here. In your view file you can either import .forms or from .forms import FormName I prefer the latter.
So, after you rename form.py to forms.py I would rewrite views.py to look like this:
from django.shortcuts import render
from .forms import FormName
def index(request):
return render(request,'basicapp/index.html')
def form_page(request):
this_form = FormName()
return render(request,'basicapp/form_page.html',{'form':this_form})
You made two mistakes in your code
1) Your form file should be named forms.py and not form.pY
2) your views.py import code should be
from django.shortcuts import render
from basicapp import forms
There is an issue in your view.py
replace
below line
from .forms import forms
with
from <your app name>.forms import forms
You are getting this error because django is trying to find it in root folder where your manage.py exist.

NameError: name doohickey is not defined

I am having issues importing a function from a module I created into my code. I am getting an error stating that the function is not defined, despite importing the module into my file.
The error message:
something = doohickey()
NameError: name 'doohickey' is not defined
get_random_tweet.py
import twitter
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_secret='')
timeline = api.GetUserTimeline(screen_name='realDonaldTrump',
include_rts=False,
trim_user=True,
exclude_replies=True,
count=6)
def doohickey():
pprint(timeline)
return {'index': "<i> something </i>"}
My views.py
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
import hello.get_random_tweet
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = doohickey()
return render(request, "index.html")
I have also attempted the following:
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
from hello.get_random_tweet import doohickey
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = doohickey()
return render(request, "index.html")
Error message:
something = doohickey()
NameError: name 'doohickey' is not defined
and
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
import hello.get_random_tweet
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = hello.get_random_tweet.doohickey()
return render(request, "index.html")
Error message:
something = hello.get_random_tweet.doohickey()
NameError: name 'doohickey' is not defined
It looks like the issue is that you are not referring to the doohickey function as part of the hello.get_random_tweet namespace. You can do this in several ways:
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
from hello.get_random_tweet import doohickey
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = doohickey()
return render(request, "index.html")
or
from django.shortcuts import render
from django.http import HttpResponse
from hello.sampled_stream import okdood
import hello.get_random_tweet
from .models import Greeting
# Create your views here.
def index(request):
# return HttpResponse('Hello from Python!')
# okdood()
something = hello.get_random_tweet.doohickey()
return render(request, "index.html")
As your code is currently structured, you import the hello.get_random_tweet module, but when you refer to doohickey Python is looking for it in the local namespace. However, it should be looking for it in the hello.get_random_tweet namespace. You can either import the function and add it to the local namespace, as shown in the first snippet, or refer to the function in the imported module's namespace as shown in the second snippet.
Might be a copy/paste error, but you're missing endquotes on a few lines here, and the closing bracket:
api = twitter.Api(consumer_key='',
consumer_secret='',
access_token_secret=''
Should be:
api = twitter.Api(consumer_key='',
consumer_secret=''
access_token_key=''
access_token_secret='')

Creating a sample application where Django Bulk Writes to Mongo Db after Sessions end

I want to be able to use Django Sessions and Mongo DB together to perform bulk writes to database after a Session. Later I want to be able to associate Users to Sessions and Events as well.
I have just started and I am new to Django . I am just running around tutorial after tutorial and so far I have just tried out some things and may have got a few things right I guess.
Any help with finding some right direction is appreciated.
Here is my views.py
# Create your views here.
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.sessions.models import Session
from django.conf import settings
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import json
class Events(APIView):
def post(self,request,format=None):
try:
event_info = json.loads(request.body)
except ValueError:
return Response(status=status.HTTP_400_BAD_REQUEST)
if not request.session.session_key:
request.session.save()
sid = str(request.session.session_key)
settings.DB.events.insert(event_info, w=1)
return Response(sid,status=status.HTTP_200_OK)
events = Events.as_view()
models.py
from __future__ import unicode_literals
from django.db import models
from django.conf import settings
# Create your models here.
from django.contrib.sessions.models import Session
from django.contrib.auth.signals import user_logged_in
class EventsModel(object):
def __init__(self):
self.conn = pymongo.MongoClient()
self.db = conn.dev_db
def save(self, event_info):
"""
Save json object into mongodb Cluster
:param event_info:
:return:
"""
self.db.events.insert(event_info, w=1)

Django serves zero byte response

This just happened to one of my sites and I have no idea what caused it.
This happens for any URL that is served by mod_wsgi for a particular application, which used to work fine.
Syntax errors in settings.py cause HTTP 500.
Syntax errors in urls.py don't influence anything—seems like this file is never loaded.
What is there to check?
The culprit was this line:
from django.contrib.auth.forms import AuthenticationForm
in middleware.py.
Moving the import into the function that uses AuthenticationForm solved the problem:
from django.http import HttpResponseRedirect
from django.conf import settings
from django.contrib import messages
from django.contrib.auth import login
#from django.contrib.auth.forms import AuthenticationForm <-- THE LINE WAS HERE
class LoginFormMiddleware(object):
def process_request(self, request):
if request.method == 'POST' and 'is_top_login_form' in request.POST:
from django.contrib.auth.forms import AuthenticationForm # <-- MOVED HERE
form = AuthenticationForm(data=request.POST)
is_valid = form.is_valid()
if is_valid:
login(request, form.get_user())
program = request.user.get_profile().first_intern.program
NavigationMiddleware.set_program(request, program)
return HttpResponseRedirect('%s?quick' % program.get_absolute_url())
else:
messages.error(request, request.POST['username'], extra_tags='login')
return HttpResponseRedirect(request.get_full_path())
I still have no idea why the code used to work, why it suddenly broke and why doing this solved the problem.
There has to be some magick in Python, after all.

Categories