I have the following problem my database is not empty and has the record that I need. But when I query the db it says that there is no such object matching the given query. I query the db from within a websocket using django-channels and my database is postgreSQL.
I am aware that there are other questions about this and I looked into them but they are all about empty database or wrong url slug which is not my case and doesn't help me with anything
Here is the corresponding code:
#channel_session_user_from_http
def ws_receive(message):
username = message.user.username
print(username)
text = json.loads(message['text']).get('text')
# Use my algorithm here
score = score_argument.get_rating(text)
# find the room with our users
current_room = get_object_or_404(PairUsers, Q(username_a=username) | Q(username_b=username))
# current_room = PairUsers.objects.filter(Q(username_a=username) | Q(username_b=username)).first()
# check which user you got and send the message to the other
if current_room.username_b == username:
current_room.score_b = score
other_channel = Channel(current_room.reply_channel_a)
message.reply_channel.send({'text': text})
other_channel.send({'text': text})
else:
current_room.score_a = score
other_channel = Channel(current_room.reply_channel_b)
message.reply_channel.send({'text': text})
other_channel.send({'text': text})
Another thing that I noticed is that the print(username) does not print anything it just skips this line. I used message.user.username in different function that works so I am sure it should return the username
Traceback:
Traceback (most recent call last):
File "C:\Program Files (x86)\Python35\lib\site-packages\channels\worker.py", line 119, in run
consumer(message, **kwargs)
File "C:\Program Files (x86)\Python35\lib\site-packages\channels\sessions.py", line 180, in inner
result = func(message, *args, **kwargs)
File "C:\Program Files (x86)\Python35\lib\site-packages\channels\auth.py", line 73, in inner
return func(message, *args, **kwargs)
File "C:\Program Files (x86)\Python35\lib\site-packages\channels\sessions.py", line 64, in inner
return func(message, *args, **kwargs)
File "C:\Program Files (x86)\Python35\lib\site-packages\channels\auth.py", line 89, in inner
return func(message, *args, **kwargs)
File "C:\Users\nithe\Desktop\debateit\play\consumers.py", line 51, in ws_receive
current_room = get_object_or_404(PairUsers, Q(username_a=username) | Q(username_b=username))
File "C:\Program Files (x86)\Python35\lib\site-packages\django\shortcuts.py", line 93, in get_object_or_404
raise Http404('No %s matches the given query.' % queryset.model._meta.object_name)
django.http.response.Http404: No PairUsers matches the given query.
message.user.username appears to be None, your query will of course fail. This question is not a database problem (yet), it's channels related.
Try printing your message.user.__dict__, see if it matches the object you expect.
Related
Imagine the follow functions, that should upload and copy something to S3
class TestAttachments(TestCase):
# YAML is the only serializer supporting binary
#override_env(AWS_DEFAULT_REGION='eu-west-1') # So the test doesn't fail depending on env. vars
#my_vcr.use_cassette(serializer='yaml')
def test_copy_attachments_to_sent_folder(self):
with self.assertRaises(
CopyAttachmentException,
msg="Failed to copy attachments to sent folder for attachment URL: http://example.com/foo.jpg"
) as cm:
copy_attachments_to_sent_folder(["http://example.com/foo.jpg"])
self.assertEqual(cm.exception.__cause__.__class__, InvalidAttachmentURL)
TEST_UUIDS = ["uuid_0"]
with patch.object(uuid, 'uuid4', side_effect=TEST_UUIDS):
result = copy_attachments_to_sent_folder([
f"https://{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}.s3.amazonaws.com/attachments/Test+video.mov"
])
self.assertEqual(
[AttachmentMetadata(
s3_key=f"attachments/sent/{TEST_UUIDS[0]}/video/quicktime/Test video.mov",
filename="Test video.mov",
mime_type="video/quicktime",
size=178653,
)],
result
)
It should test the following function:
def copy_attachments_to_sent_folder(urls: List[str]) -> List[AttachmentMetadata]:
# Copy the attachment to the sent folder in parallel
with futures.ThreadPoolExecutor(max_workers=4) as executor:
urls_by_future = {executor.submit(copy_attachment_to_sent_folder, url): url for url in urls}
results_by_url = {}
for future in futures.as_completed(urls_by_future.keys()):
try:
results_by_url[urls_by_future[future]] = future.result()
except Exception as e:
raise CopyAttachmentException(
f"Failed to copy attachments to sent folder for attachment URL: {urls_by_future[future]}"
) from e
# The futures can complete out-of-order, so we need to re-order them to match the original order here
return [results_by_url[url] for url in urls]
Which finally uses this function inside:
def copy_attachment_to_sent_folder(url: str) -> AttachmentMetadata:
aws_session = attachments_aws_session()
s3_client = aws_session.client("s3")
parse_result = urlparse(url, allow_fragments=False)
# Allow both with/without AWS region in hostname
attachment_hostname_regex = fr"{settings.MESSAGE_ATTACHMENTS_S3_BUCKET}\.s3\.(.+?\.)?amazonaws\.com"
if not (
parse_result.hostname is not None and re.fullmatch(attachment_hostname_regex, parse_result.hostname) is not None
and parse_result.scheme == "https"
):
raise InvalidAttachmentURL(f"URL {url} is not a valid attachment URL")
path = unquote_plus(parse_result.path)
key = path.lstrip("/")
_, _, filename = key.rpartition("/")
object_metadata = get_s3_object_metadata(aws_session=aws_session, object_bucket=settings.MESSAGE_ATTACHMENTS_S3_BUCKET,
object_key=key)
s3_resource = aws_session.resource("s3")
# Place images in their own path so that provider1 only has access to these files
destination_key = f"attachments/sent/{uuid.uuid4()}/{object_metadata.mime_type}/{filename}"
try:
# Copy to sent attachments folder and set content-type
response = s3_resource.Object(settings.MESSAGE_ATTACHMENTS_S3_BUCKET, destination_key).copy_from(
# Tell S3 to set cache header to "Forever"
Expires=datetime(2100, 1, 1),
CopySource={"Bucket": settings.MESSAGE_ATTACHMENTS_S3_BUCKET, "Key": key},
ACL="private",
MetadataDirective="REPLACE",
# Set mime type on the destination file
ContentType=object_metadata.mime_type,
# Only copy it if the user did not modify the file since we fetched it to detect mimetype :)
# S3 allows overwriting of the files. A user could potentially overwrite
# the already uploaded file with a file of a different type after they upload it and after we detect the
# mimetype, but before we copy it to the destination. Setting CopySourceIfUnmodifiedSince prevents that.
CopySourceIfUnmodifiedSince=object_metadata.last_modified,
)
except ClientError as e:
raise CopyAttachmentException from e
if response.get("CopyObjectResult", {}).get("ETag", None) is None:
raise CopyAttachmentException(
f"Copy of object '{key}' to '{destination_key}' was not successful. Response: {response}"
)
return AttachmentMetadata(
s3_key=destination_key,
filename=filename,
mime_type=object_metadata.mime_type,
size=object_metadata.byte_size,
)
This works super fine on botocore==1.23.46
But as soon as we upgrade it, we get presented with the following error:
Error
Traceback (most recent call last):
File "/tl/test/messaging/attachments.py", line 105, in copy_attachments_to_sent_folder
results_by_url[urls_by_future[future]] = future.result()
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/concurrent/futures/_base.py", line 439, in result
return self.__get_result()
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/concurrent/futures/_base.py", line 391, in __get_result
raise self._exception
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/concurrent/futures/thread.py", line 58, in run
result = self.fn(*self.args, **self.kwargs)
File "/tl/test/messaging/attachments.py", line 64, in copy_attachment_to_sent_folder
destination_key = f"attachments/sent/{uuid.uuid4()}/{object_metadata.mime_type}/{filename}"
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/unittest/mock.py", line 1104, in __call__
return self._mock_call(*args, **kwargs)
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/unittest/mock.py", line 1108, in _mock_call
return self._execute_mock_call(*args, **kwargs)
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/unittest/mock.py", line 1165, in _execute_mock_call
result = next(effect)
StopIteration
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/tl/.pyenv/versions/3.10.2/lib/python3.10/contextlib.py", line 79, in inner
return func(*args, **kwds)
File "/tl/test/venv/lib/python3.10/site-packages/vcr/cassette.py", line 100, in __call__
return type(self)(self.cls, args_getter)._execute_function(function, args, kwargs)
File "/tl/test/venv/lib/python3.10/site-packages/vcr/cassette.py", line 114, in _execute_function
return self._handle_function(fn=handle_function)
File "/tl/test/venv/lib/python3.10/site-packages/vcr/cassette.py", line 138, in _handle_function
return fn(cassette)
File "/tl/test/venv/lib/python3.10/site-packages/vcr/cassette.py", line 107, in handle_function
return function(*args, **kwargs)
File "/tl/test/messaging/test_attachments.py", line 27, in test_copy_attachments_to_sent_folder
result = copy_attachments_to_sent_folder([
File "/tl/test/messaging/attachments.py", line 107, in copy_attachments_to_sent_folder
raise CopyAttachmentException(
messaging.attachments.CopyAttachmentException: Failed to copy attachments to sent folder for attachment URL: https://test-message-attachments.s3.amazonaws.com/attachments/Test+video.mov
I assume it has to do with destination_key = f"attachments/sent/{uuid.uuid4()}/{object_metadata.mime_type}/{filename}" but I am not sure what I am doing wrong? And why exactly it works on botocore==<1.2.46 and not after.
I am working with a mobile game API and a Telegram Bot. It worked when I put in a fixed Clantag, but now I wanted to let the user write a tag and add it to the link. The app then should search for the clan and get the right stats. Everything is ok but I get this message now and cannot find my mistake. Would be happy if you could help!
def main():
last_update_id = None
message = ""
while True:
updates = get_updates(last_update_id)
if len(updates["result"]) > 0:
last_update_id = get_last_update_id(updates) + 1
message = get_last_update_Message(updates)
clan_stats(updates, message)
def get_last_update_Message(updates):
message = ""
for update in updates["result"]:
message = update["message"]
return message["text"]
def clan_stats(updates, ID):
#https://api.royaleapi.com/clan/1RLU78YU
Link = '"https://api.royaleapi.com/clan/' + ID + '"'
r=requests.get(Link, headers={"Accept":"application/json",
"authorization":"Bearer TOKENHERE"})
clan = r.json()
Full Traceback:
Traceback (most recent call last):
File "/home/Lee63225/clashroyaleclanbot.py", line 188, in <module>
main()
File "/home/Lee63225/clashroyaleclanbot.py", line 184, in main
clan_stats(updates, message)
File "/home/Lee63225/clashroyaleclanbot.py", line 80, in clan_stats
"authorization":"Bearer TOKENHERE"})
File "/usr/lib/python3.7/site-packages/requests/api.py", line 72, in get
return request('get', url, params=params, **kwargs)
File "/usr/lib/python3.7/site-packages/requests/api.py", line 58, in request
return session.request(method=method, url=url, **kwargs)
File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 503, in request
prep.url, proxies, stream, verify, cert
File "/usr/lib/python3.7/site-packages/requests/sessions.py", line 676, in merge_environment_settings
env_proxies = get_environ_proxies(url, no_proxy=no_proxy)
File "/usr/lib/python3.7/site-packages/requests/utils.py", line 760, in get_environ_proxies
if should_bypass_proxies(url, no_proxy=no_proxy):
File "/usr/lib/python3.7/site-packages/requests/utils.py", line 716, in should_bypass_proxies
if is_ipv4_address(parsed.hostname):
File "/usr/lib/python3.7/site-packages/requests/utils.py", line 640, in is_ipv4_address
socket.inet_aton(string_ip)
TypeError: inet_aton() argument 1 must be str, not None
Thank you!
I think it should rather be
Link = 'https://api.royaleapi.com/clan/' + ID
There is some surrounding " in your attempt.
But now as I look, the function is called as clan_stats(update,message). That "message" should be a clantag, make sure it is (as now it comes from get_last_update_Message(), and looks very suspicious.
I have an issue with my bot:
I want to authorize user via phone_request. But it crashes. Although I get user phone. By phone_request I mean that I'm asking user for a phone number with this:
def get_keyboard():
contact_button = KeyboardButton('Start conversation',
request_contact=True)
reply_keyboard = [[contact_button]]
return reply_keyboard
I catch it with this:
dp.add_handler(MessageHandler(Filters.contact,
contact_callback,pass_user_data=True))
Than it goes there:
def contact_callback(bot, update):
contact = update.effective_message.contact
phone = contact.phone_number
print(contact)
print(phone)
update.message.reply_text('Thanks your data is accepted', get_authorized(), resize_keyboard=True)
get_authorized is simply this:
def get_authorized():
reply_keyboard = [['Pay', 'Why I'm in debt'], ['Remind Later']]
return reply_keyboard
What can go wrong here?
Traceback:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/telegram/ext/dispatcher.py", line 279, in process_update
handler.handle_update(update, self)
File "/usr/local/lib/python3.5/dist-packages/telegram/ext/messagehandler.py", line 169, in handle_update
return self.callback(dispatcher.bot, update, **optional_args)
File "/home/ubuntu/Telegram_bot_OSDI/Telegram_Bot_OSDI_22.py", line 164, in contact_callback
update.message.reply_text('Спасибо! Ваши данные приняты', get_authorized(), resize_keyboard=True)
File "/usr/local/lib/python3.5/dist-packages/telegram/message.py", line 455, in reply_text
return self.bot.send_message(self.chat_id, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/telegram/bot.py", line 65, in decorator
result = func(self, *args, **kwargs)
File "/usr/local/lib/python3.5/dist-packages/telegram/bot.py", line 90, in decorator
result = self._request.post(url, data, timeout=kwargs.get('timeout'))
File "/usr/local/lib/python3.5/dist-packages/telegram/utils/request.py", line 309, in post
headers={'Content-Type': 'application/json'})
File "/usr/local/lib/python3.5/dist-packages/telegram/utils/request.py", line 223, in _request_wrapper
raise BadRequest(message)
telegram.error.BadRequest: Unsupported parse_mode
I'm not able to pass the user input into JQL query? I've tried no of alternative but nothing works.
Here is the code.
project_name=raw_input("Please give the project name: ")
reporter_name=raw_input("Please provide the name of creator: ")
date_from=raw_input("Please provide the time interval for which you want issues: From ")
date_to=raw_input("Please provide the time interval for which you want issues: To ")"""
total_issues = jira.search_issues('project = %s AND reporter = %s AND created > %s and created < %s' % (projectname, reportername, datefrom, dateto))
print total_issues
It gives me: jira.exceptions.JIRAError
traceback (most recent call last):
File "jiradetailsizmirtomtom.py", line 27, in <module>
for i in jira.search_issues('project = project_name AND reporter = reporter_name AND created > date_from and created < date_to'):
File "/Library/Python/2.7/site-packages/jira/client.py", line 1747, in search_issues
issues = self._fetch_pages(Issue, 'issues', 'search', startAt, maxResults, search_params)
File "/Library/Python/2.7/site-packages/jira/client.py", line 397, in _fetch_pages
resource = self._get_json(request_path, params=page_params, base=base)
File "/Library/Python/2.7/site-packages/jira/client.py", line 2172, in _get_json
r = self._session.get(url, params=params)
File "/Library/Python/2.7/site-packages/jira/resilientsession.py", line 150, in get
return self.__verb('GET', url, **kwargs)
File "/Library/Python/2.7/site-packages/jira/resilientsession.py", line 146, in __verb
raise_on_error(response, verb=verb, **kwargs)
File "/Library/Python/2.7/site-packages/jira/resilientsession.py", line 56, in raise_on_error
r.status_code, error, r.url, request=request, response=r, **kwargs)
jira.exceptions.JIRAError
Can we really pass variable to JQL query? Does JQL allows this?
The error happens when trying to take a quiz. Although the attribute error of my page is the same as in this topic, the solution has not solved my problem.
I've tried the solution mentioned in the topic above but it hasn't solved my problem. I've mixed all the apps in that Django Quiz in one, having the models in the same file and so on. For the moment it has worked properly, and I've been able to manage the settings in the 'admin' page without any problem.
The issue relies on when taking the quiz, I recieve this traceback:
Internal Server Error: /myquiz/take/
Traceback (most recent call last):
File "C:\P4\myapp\models.py", line 359, in user_sitting
sitting = self.get(user=user, quiz=quiz, complete=False)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\manager.py", line 122, in manager_method
return getattr(self.get_queryset(), name)(*args, **kwargs)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\query.py", line 387, in get
self.model._meta.object_name
myapp.models.DoesNotExist: Sitting matching query does not exist.
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\P4\myapp\views.py", line 163, in dispatch
self.quiz)
File "C:\P4\myapp\models.py", line 361, in user_sitting
sitting = self.new_sitting(user, quiz)
File "C:\P4\myapp\models.py", line 339, in new_sitting
questions = ",".join(map(str, questions_set)) + ","
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\query.py", line 258, in __iter__
self._fetch_all()
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\db\models\query.py", line 1074, in _fetch_all
self._result_cache = list(self.iterator())
File "C:\Python\lib\site-packages\model_utils\managers.py", line 80, in iterator
sub_obj = self._get_sub_obj_recurse(obj, s)
File "C:\Python\lib\site-packages\model_utils\managers.py", line 153, in _get_sub_obj_recurse
node = getattr(obj, rel)
AttributeError: 'int' object has no attribute 'essay_question'
It seems like the problem might be in essay_question model or in Sitting model. However, I can't find an answer to this problem. Here there are the pieces of code I think that are related with the error, but if more are needed just ask (most of the parts remain the same of the Quiz app of Django).
Sitting manager model:
class SittingManager(models.Manager):
def new_sitting(self, user, quiz):
if quiz.random_order is True:
questions_set = quiz.questions_set.all() \
.select_subclasses() \
.order_by('?')
else:
questions_set = quiz.questions_set.all() \
.select_subclasses()
questions_set = questions_set.values_list('id', flat=True)
if questions_set.count() == 0:
raise ImproperlyConfigured('Question set of the quiz is empty. '
'Please configure questions properly')
if quiz.max_questions and quiz.max_questions < questions_set.count():
questions_set = questions_set[:quiz.max_questions]
questions = ",".join(map(str, questions_set)) + ","
new_sitting = self.create(user=user,
quiz=quiz,
question_order=questions,
question_list=questions,
incorrect_questions="",
current_score=0,
complete=False,
user_answers='{}')
return new_sitting
def user_sitting(self, user, quiz):
if quiz.single_attempt is True and self.filter(user=user,
quiz=quiz,
complete=True)\
.exists():
return False
try:
sitting = self.get(user=user, quiz=quiz, complete=False)
except Sitting.DoesNotExist:
sitting = self.new_sitting(user, quiz)
except Sitting.MultipleObjectsReturned:
sitting = self.filter(user=user, quiz=quiz, complete=False)[0]
return sitting
And the QuizTake view:
EDITED
I would appreciate an answer since it's not the same solution of the other similar error with this app. I would provide more needed info and thank you for the help.
.
EDIT 2:
I'm getting this now while trying to get to 'myquiz/take' view:
Internal Server Error: /myquiz/take/
Traceback (most recent call last):
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 149, in get_response
response = self.process_exception_by_middleware(e, request)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\core\handlers\base.py", line 147, in get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\base.py", line 68, in view
return self.dispatch(request, *args, **kwargs)
File "C:\P4\myapp\views.py", line 171, in dispatch
return super(QuizTake, self).dispatch(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\base.py", line 88, in dispatch
return handler(request, *args, **kwargs)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\edit.py", line 213, in get
return self.render_to_response(self.get_context_data())
File "C:\P4\myapp\views.py", line 206, in get_context_data
context = super(QuizTake, self).get_context_data(**kwargs)
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\edit.py", line 122, in get_context_data
kwargs['form'] = self.get_form()
File "C:\Python\lib\site-packages\django-1.9.1-py3.5.egg\django\views\generic\edit.py", line 35, in get_form_with_form_class
return get_form(self, form_class=form_class)
File "C:\P4\myapp\views.py", line 184, in get_form
return form_class(**self.get_form_kwargs())
TypeError: __init__() missing 1 required positional argument: 'question'
Here are extracts of my views.py (which seem to be causing the error):
def dispatch(self, request, *args, **kwargs):
self.quiz = get_object_or_404(Quiz, url=self.kwargs['quiz_name'])
if self.quiz.draft and not request.user.has_perm('quiz.change_quiz'):
raise PermissionDenied
self.logged_in_user = self.request.user.is_authenticated()
if self.logged_in_user:
self.sitting = Sitting.objects.user_sitting(request.user,
self.quiz)
else:
self.sitting = self.anon_load_sitting()
if self.sitting is False:
return render(request, 'single_complete.html')
return super(QuizTake, self).dispatch(request, *args, **kwargs)
Get_form:
def get_form(self, form_class):
if self.logged_in_user:
self.questions = self.sitting.get_first_questions()
self.progress = self.sitting.progress()
else:
self.questions = self.anon_next_questions()
self.progress = self.anon_sitting_progress()
if self.questions.__class__ is Essay_Questions:
form_class = EssayForm
return form_class(**self.get_form_kwargs())
def get_form_kwargs(self):
kwargs = super(QuizTake, self).get_form_kwargs()
return dict(kwargs, questions=self.questions)
FORM_VALID and get_context_data
def form_valid(self, form):
if self.logged_in_user:
self.form_valid_user(form)
if self.sitting.get_first_questions() is False:
return self.final_result_user()
else:
self.form_valid_anon(form)
if not self.request.session[self.quiz.anon_q_list()]:
return self.final_result_anon()
self.request.POST = {}
return super(QuizTake, self).get(self, self.request)
def get_context_data(self, **kwargs):
context = super(QuizTake, self).get_context_data(**kwargs)
context['question'] = self.questions
context['quiz'] = self.quiz
if hasattr(self, 'previous'):
context['previous'] = self.previous
if hasattr(self, 'progress'):
context['progress'] = self.progress
return context
myapp.models.DoesNotExist: Sitting matching query does not exist.
This means exactly what it says. YOu are trying to fetch a Sitting object that does not exist. So you need to sorround line 359 with try except to handle that situation cleanly. In fact you can simplify that whole method as follows.
def user_sitting(self, user, quiz):
if quiz.single_attempt is True and self.filter(user=user,
quiz=quiz,
complete=True)\
.exists():
return False
try:
return self.filter(user=user,quiz=quiz,complete=True)[0]
except IndexError:
return sitting = self.new_sitting(user, quiz)
Simpler code is easier to maintain and you are cutting down the number of queries, which leads to a performance improvement.
AttributeError: 'int' object has no attribute 'essay_question'
What this means is that you think you h have a Questions instance but what you actually have is a meta. The rest of the stacktrace gives you the lines of execution that lead to this error. Look at the lines that mention your own code, some where near they you are calling a method that should return a Questions instance but returns int instead.
The reason that it used to work and doesn't work anymore is what's known as a regression error. Changes to some section of code has made another section misbehave. The most popular, sustainable way to tackle them is with unit testing.