I'm using django 1.4, and python 2.7
I'm trying to get data from the MySQL database...
views.py:
def myRequests(request):
#request = ProjectRequest.objects
response = render_to_response('myRequests.html', {'ProjectRequest': request}, context_instance = RequestContext(request))
return response
As soon as I uncomment 'request = ProjectRequest.objects' I get the error:
AttributeError at /myRequests/
'Manager' object has no attribute 'META'
I'm not defining any new user models so this error makes no sense to me.
Exception location:
/{path}/lib/python2.7/site-packages/django/core/context_processors.py in debug, line 35
modelsRequest.py:
class ProjectRequest(Model):
reqType = CharField("Request Type", max_length = MAX_CHAR_LENGTH)
reqID = IntegerField("Request ID", primary_key = True)
ownerID = IntegerField("Owner ID")
projCodeName = CharField("Project Code Name", max_length = MAX_CHAR_LENGTH)
projPhase = CharField("Project Phase", max_length = MAX_CHAR_LENGTH)
projType = CharField("Project Phase", max_length = MAX_CHAR_LENGTH)
projNotes = CharField("Project Notes", max_length = MAX_CHAR_LENGTH)
contacts = CharField("Project Notes", max_length = MAX_CHAR_LENGTH)
reqStatus = CharField("Status", max_length = MAX_CHAR_LENGTH)
reqPriority = CharField("Request Priority", max_length = MAX_CHAR_LENGTH)
reqEstDate = DateTimeField("Request Estimated Complete Date", auto_now_add = True)
lastSaved = DateTimeField("Last saved", auto_now = True)
created = DateTimeField("Created", auto_now_add = True)
def __unicode__(self):
return str(self.reqID) + ": " + str(self.reqType)
class Meta:
app_label = 'djangoTestApp'
db_table = 'requests'
Any idea what's going on?!
Use a different variable name
project_request = ProjectRequest.objects
The issue is because of this context_instance = RequestContext(request)
It loses context of the request object as it has been overwritten. Hence the issue.
def myRequests(request):
project_request = ProjectRequest.objects
#Now you have access to request object,
# do whatever you want with project_request -
response = render_to_response('myRequests.html', {'ProjectRequest': project_request}, context_instance = RequestContext(request))
return response
The reason you are getting the error 'Manager' object has no attribute 'META' is, when you do
ProjectRequest.objects
the default manager (objects) for models ProjectRequest is assign to the (overwritten) local variable request.
Related
When I save my NoteForm, I want to save my form and the "note" field, then I want to create a "tag" for the Note in the NoteTagModel.
At the moment, I create a new tag but it is not assigned to the note. I know that the following code must be wrong:
notetag.id = new_note_parse.id
If I change to:
notetag.note = new_note_parse.id
I receive the following error:
"NoteTagModel.note" must be a "NoteModel" instance.
The below is my views.py:
def notes(request):
note_form = NoteForm
notetag = NoteTagModel()
note_form=NoteForm(request.POST)
if note_form.is_valid():
new_note = note_form.save(commit=False)
new_note_parse = new_note
new_note.save()
notetag.id = new_note_parse.id
notetag.tag = "Test"
notetag.save()
return HttpResponseRedirect(reverse('notes:notes'))
context = {
'note_form' : note_form,
'notes' : NoteModel.objects.all(),
'notes_tag' : NoteTagModel.objects.all(),
}
return render(request, "notes/notes.html", context)
My models.py is:
class NoteModel(models.Model):
note = models.CharField(
max_length = 5000
)
def __str__(self):
return f"{self.note}"
class NoteTagModel(models.Model):
note = models.ForeignKey(
NoteModel,
on_delete=models.CASCADE,
related_name="notes",
blank= False,
null = True,
)
tag = models.CharField(
max_length = 5000
)
def __str__(self):
return f"Note: {self.note} | Tag: {self.tag}"
I have the following as my forms.py:
class NoteForm(ModelForm):
class Meta:
model = NoteModel
fields = [
'note',
]
Change views.py to reflect the below:
note = NoteModel.objects.get(id=new_note_parse.id)
notetag.note = note
I am working on a giveaway bot and after doing the start and reroll command I have run into the end command , which i cannot fully grasp how to do it. I thought to register something when the giveaway is created (msgID of the giveaway im registering) in my aiosqlite database and for the end function , i could be able to fetch it and stop the giveaway. Now here is the thing, i cant think of a function or a task that will end the giveaway or somehow just end the duration.
For reference here is my start command :
class Start(commands.Cog):
def __init__(self, client):
self.client = client
def convert(self, timer):
pos = ["s", "m", "h", "d"]
time_dict = {"s" : 1, "m" : 60, "h" : 3600, "d" : 3600*24}
unit = timer[-1]
if unit not in pos:
return -1
try:
val = int(timer[:-1])
except:
return -2
return val * time_dict[unit]
#commands.command()
async def start(self, ctx, duration, winners: str, *, prize):
timer = (self.convert(duration))
winners = int(winners.replace("w",""))
await ctx.message.delete()
timestamp = time.time() + timer
epoch_time = int((time.time() + timer))
embed = discord.Embed(title = f"{prize}", description = f'React with 🎉 to enter\nEnds: <t:{epoch_time}:R> (<t:{epoch_time}>)\nHosted by {ctx.author.mention}\n', color =
ctx.author.color, timestamp=(datetime.datetime.utcfromtimestamp(timestamp)))
embed.set_footer(text=f'Winners : {winners} | Ends at \u200b')
gaw_msg = await ctx.send(content = "<:spadess:939938117736091678> **GIVEAWAY** <:spadess:939938117736091678>",embed=embed)
await gaw_msg.add_reaction("🎉")
db = await aiosqlite.connect("main.db")
cursor = await db.cursor()
await cursor.execute(f'SELECT * FROM storingStuff WHERE msgID = {gaw_msg.id}')
data = await cursor.fetchone()
if data is None:
await cursor.execute(f'INSERT INTO storingStuff (msgID, guildID) VALUES({gaw_msg.guild.id} , {gaw_msg.id})')
await db.commit()
await cursor.close()
await db.close()
await asyncio.sleep(timer)
new_msg = await ctx.channel.fetch_message(gaw_msg.id)
users_mention = []
for i in range(winners):
users = await new_msg.reactions[0].users().flatten()
users.pop(users.index(self.client.user))
winner = random.choice(users)
users_mention.append(winner.mention)
users.remove(winner)
displayed_winners = ",".join(users_mention)
endembed = discord.Embed(title=f"{prize}", description=f"Winner: {displayed_winners}\nHosted by: {ctx.author.mention}", color = ctx.author.color, timestamp=(datetime.datetime.utcfromtimestamp(timestamp)))
endembed.set_footer(text= 'Ended at \u200b')
await gaw_msg.edit(content = "<:done:939940228746072096> **GIVEAWAY ENDED** <:done:939940228746072096>",embed=endembed)
await ctx.send(f"Congragulations {displayed_winners}! You won the **{prize}**.\n{gaw_msg.jump_url}")
def setup(client):
client.add_cog(Start(client))
Any help with the case would be appreciated , or any code reference as I'm pretty new. Thank you for spending your time and reading this.
I'm trying to make an app that uses data from MySQL server. So far I was doing fine, until I stumbled accross a need to update the Labels.
This is what I have so far:
from kivy.uix.button import Button
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.label import Label
from kivy.uix.scrollview import ScrollView
from kivy.clock import Clock
import MySQLdb
class MainView(ScrollView):
def qchange(self):
query = 'SELECT * FROM `citiestovisit` ORDER BY `idcitiestovisit`'
self.db_data(query)
q = 'SELECT * FROM `citiestovisit` ORDER BY `Name`'
def db_data(self, query=q):
#vector = ListProperty()
vector = []
con = MySQLdb.connect(host="localhost", user="root", passwd="", db="cities")
cur = con.cursor()
cur.execute('SET NAMES `utf8`')
cur.execute(query)
result = cur.fetchall()
for row in result:
string = str(row[0]) + " " + str(row[1]) + " " + str(row[2])
vector.append(string)
print vector
return vector
def __init__(self, **kwargs):
kwargs['cols'] = 2
super(MainView, self).__init__(**kwargs)
GL = GridLayout(cols = 3, spacing=10, size_hint_y=None)
GL.bind(minimum_height=GL.setter('height'))
for row in self.db_data():
splitRow = row.split(" ")
for data in splitRow:
GL.add_widget(Label(text=data,size_hint_y=None, font_size='20sp'))
self.add_widget(GL)
Builder.load_string("""
<MenuScreen>:
BoxLayout:
GridLayout:
cols: 1
Button:
text: 'Goto settings'
on_press:
root.manager.transition.direction = 'left'
root.manager.current = 'settings'
Button:
text: 'Quit'
Label:
font_name: 'C:\Anonymous\Anonymous.ttf'
text: "picture here"
<SettingsScreen>:
""")
# Declare both screens
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
pass
ss = SettingsScreen(name='settings')
layout = BoxLayout(orientation='vertical')
BL = BoxLayout()
layout.add_widget(BL)
#Instance of a MainView class
MV = MainView()
def callback(instance):
sm.transition.direction = 'right'
sm.current = 'menu'
def callback2(instance):
MV.qchange()
btn = Button(text="Back to Menu")
btn.bind(on_press=callback)
btn.size_hint = (1, 0.3)
BL.add_widget(btn)
btn2 = Button(text="Sort by ID")
btn2.size_hint = (1, 0.3)
btn2.bind(on_press=callback2)
BL.add_widget(btn2)
layout.add_widget(MainView())
sublayout = GridLayout(cols=3)
sublayout.add_widget(Label(text="hello"))
sublayout.add_widget(Label(text="World"))
sublayout.add_widget(Label(text="Python"))
layout.add_widget(sublayout)
ss.add_widget(layout)
# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(ss)
class MyApp(App):
def build(self):
return sm
if __name__ == '__main__':
MyApp().run()
I'm particularly interested in def qchange(self) mehod as it passes into def db_data(self, query=q) a new query; as a result request is sent to the database and an array of strings is returned. However, this array is not proccessed any further and labels in GL widget are not updated. I think I need to add the clock that would call the __init__ in MainView, but it's only a guess as I've also read about using properties (which I don't know how to use here as well)
I've eddited my code. Now it looks like this:
class MainView(ScrollView):
def qchange(self):
query = 'SELECT * FROM `citiestovisit` ORDER BY `idcitiestovisit`'
#self.db_data(query)
#LG = self.LabelsGrid(self.GL)
q = 'SELECT * FROM `citiestovisit` ORDER BY `Name`'
def db_data(self, query=q):
vector = []
con = MySQLdb.connect(host="localhost", user="root", passwd="", db="cities")
cur = con.cursor()
cur.execute('SET NAMES `utf8`')
cur.execute(query)
result = cur.fetchall()
for row in result:
string = str(row[0]) + " " + str(row[1]) + " " + str(row[2])
vector.append(string)
print vector
return vector
class LabelsGrid(GridLayout):
def __init__(self, **kwargs):
self.cols = 3
self.spacing = 10
self.size_hint_y = None
def show_labels(self, strings):
self.clear_widgets()
for row in strings:
splitRow = row.split(" ")
for data in splitRow:
label = Label(text=data, size_hint_y=None, font_size='20sp')
self.add_widget(label)
GL = LabelsGrid()
def __init__(self, **kwargs):
kwargs['cols'] = 2
super(MainView, self).__init__(**kwargs)
self.GL=self.LabelsGrid()
# GL = GridLayout(cols = 3, spacing=10, size_hint_y=None)
self.GL.bind(minimum_height=self.GL.setter('height'))
self.GL.show_labels(self.db_data(self.q))
self.add_widget(self.GL)
#self.GL.clear_widgets()
Builder.load_string("""
<MenuScreen>:
BoxLayout:
GridLayout:
cols: 1
Button:
text: 'Goto settings'
on_press:
root.manager.transition.direction = 'left'
root.manager.current = 'settings'
Button:
text: 'Quit'
Label:
font_name: 'C:\Anonymous\Anonymous.ttf'
text: "picture here"
<SettingsScreen>:
""")
# Declare both screens
class MenuScreen(Screen):
pass
class SettingsScreen(Screen):
pass
ss = SettingsScreen(name='settings')
layout = BoxLayout(orientation='vertical')
BL = BoxLayout()
layout.add_widget(BL)
#Instance of a MainView class
MV = MainView()
def callback(instance):
sm.transition.direction = 'right'
sm.current = 'menu'
def callback2(instance):
MV.qchange()
btn = Button(text="Back to Menu")
btn.bind(on_press=callback)
btn.size_hint = (1, 0.3)
BL.add_widget(btn)
btn2 = Button(text="Sort by ID")
btn2.size_hint = (1, 0.3)
btn2.bind(on_press=callback2)
BL.add_widget(btn2)
layout.add_widget(MainView())
sublayout = GridLayout(cols=3)
sublayout.add_widget(Label(text="hello"))
sublayout.add_widget(Label(text="World"))
sublayout.add_widget(Label(text="Python"))
layout.add_widget(sublayout)
ss.add_widget(layout)
# Create the screen manager
sm = ScreenManager()
sm.add_widget(MenuScreen(name='menu'))
sm.add_widget(ss)
class MyApp(App):
def build(self):
return sm
if __name__ == '__main__':
MyApp().run()
By adding
class LabelsGrid(GridLayout):
def __init__(self, **kwargs):
self.cols = 3
self.spacing = 10
self.size_hint_y = None
def show_labels(self, strings):
self.clear_widgets()
for row in strings:
splitRow = row.split(" ")
for data in splitRow:
label = Label(text=data, size_hint_y=None, font_size='20sp')
self.add_widget(label)
I wanted to add custom GridLayout according to a given piece of advice, however, now I get an error saying:
AttributeError: 'LabelsGrid' object has no attribute '_trigger_layout'
Any ideas on how to handle this?
Create a custom grid layout, let's say LabelsGrid, and in the class implement a method show_labels. Example:
class LabelsGrid(GridLayout):
def show_labels(self, strings):
self.clear_widgets()
for text in strings:
label = Label(text=text)
self.add_widget(label)
This way, each time you call the method with names of labels in a list, it will update itself.
Hi i have a problem with my code that i get a error in a loop that works for a few times but then throws me a typeerro: string indices must be integers.
I want to call an api to get a json back and get some parts of the json response. heres the code:
class API(object):
def __init__(self, api_key):
self.api_key = api_key
def _request(self, api_url, params={}):
args = {'api_key': self.api_key}
for key, value in params.items():
if key not in args:
args[key] = value
response = requests.get(
Consts.URL['base'].format(
url=api_url
),
params=args
)
if response.status_code == requests.codes.ok:
return response.json()
else:
return "not possible"
print(response.url)
def get_list(self):
excel = EXCEL('s6.xlsx')
api_url = Consts.URL['list'].format(
version = Consts.API_VERSIONS['matchversion'],
start = excel.get_gamenr()
)
return self._request(api_url)
def get_match(self, matchid):
idlist = matchid
api_url = Consts.URL['match'].format(
version = Consts.API_VERSIONS['matchversion'],
matchId = idlist
)
return self._request(api_url)
def match_ids(self):
api = API('c6ea2f68-7ed6-40fa-9b99-fd591c55c05f')
x = api.get_list()
y = x['matches']
count = len(y)
ids = []
while count > 0:
count = count - 1
temp = y[0]
ids.append(temp['matchId'])
del y[0]
return ids
def match_info(self):
matchids = self.match_ids()
print(matchids)
matchinfolist = {}
counter = 1
for gameids in matchids:
info = self.get_match(gameids)
myid = self.find_partid(info['participantIdentities'])
prepdstats = info['participants'][myid-1]
print(prepdstats)
matchinfolist['stats' + str(counter)] = prepdstats
return matchinfolist
def find_partid(self, partlist):
partid = 0
idlist = partlist
while partid < 10:
partid = partid + 1
tempplayer = idlist[0]['player']
if tempplayer['summonerId'] == 19204660:
playernr = partid
partid = 500
del idlist[0]
return playernr
when i run the match_info() function i get this error
Traceback (most recent call last):
File "C:\Users\Niklas\Desktop\python riot\main.py", line 17, in <module>
main()
File "C:\Users\Niklas\Desktop\python riot\main.py", line 10, in main
print(api.match_info())
File "C:\Users\Niklas\Desktop\python riot\api.py", line 78, in match_info
myid = self.find_partid(info['participantIdentities'])
TypeError: string indices must be integers
but only after the loop in the function has run for a few times. I have no idea what im doing wrong. Any help would be nice.
Here is a link to the json: https://euw.api.pvp.net/api/lol/euw/v2.2/match/2492271473?api_key=c6ea2f68-7ed6-40fa-9b99-fd591c55c05f
The error shows up on
myid = self.find_partid(info['participantIdentities'])
For this line to execute, info must be a mapping with string keys, not a string itself. info is
info = self.get_match(gameids)
get_match ends with
return self._request(api_url)
_request ends with
if response.status_code == requests.codes.ok:
return response.json()
else:
return "not possible"
For the loop to ever run, response.json() must be a dict with key 'participantIdentities'. Your bug is expecting that to always be true.
One fix might be to make the expectation always ture. If there is a satisfactory default value, return {'participantIdentities': <default value>}. Otherwise, return None and change the loop to
info = self.get_match(gameids)
if info is not None:
# as before
else:
# whatever default action you want
This is my models.py
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
class Meta:
db_table = 'CfitUser'
def __str__(self):
return "%s's profile" % self.user
#receiver(post_save, sender=User)
def create_cfituser(sender, instance, created, **kwargs):
if created:
Cfituser.objects.get_or_create(user=instance)
This is my views.py
#api_view(['GET', 'POST'])
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
cfituser = Cfituser.objects.get(user = user)
cfituser.accesstoken = serializer.data['accesstoken']
cfituser.socialid = serializer.data['socialid']
cfituser.save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
Whenever there is a HTTP Post request, my database tables are filled in as expected but this error keeps popping up. I've tried almost every solution available on SO but I'm stuck with this.
I have tried user = models.OneToOneField(User, null = True) but this leads to two entries in my database table, one with user_id = NULL and one with user_id = actualvalue.
Any suggestions on how to fix this?
Saving by default commits the entry to the database, to prevent that, pass commit=False to save(), and then do your customizations.
serializer = serializer.save(commit=False)
user, created = User.objects.get_or_create(username = serializer.socialid)
cfituser, created = Cfituser.objects.get_or_create(user = user)
# cfituser.user = user This line is unnecessary
cfituser.accesstoken = serializer.accesstoken
cfituser.socialid = serializer.socialid
cfituser.save()
serializer.save()
You are also duplicating your efforts because your signal will also attempt to create a user. If you are on django 1.5, use customized user model; and for social registration/oauth, use django-social-auth.
OneToOneField means, in Cfituser.user the reverse side of the relation will directly return a single object(user.cfituser gives Cfituser). SO Cfituser.user must be unique through out the table(one and only one).
class Cfituser(models.Model):
user = models.OneToOneField(User)
socialid = models.IntegerField(null=True)
accesstoken = models.CharField(max_length=255L, null = True)
def __unicode__(self):
return "%s's profile" % self.user.username
def users_create(request, format = None):
"""
List all users, or create a new user.
"""
if request.method == 'GET':
cfituser = Cfituser.objects.all()
serializer = CfituserSerializer(cfituser, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = CfituserSerializer(data=request.DATA)
if serializer.is_valid():
print serializer.data
user = User.objects.create_user(username = serializer.data['socialid'])
Cfituser(user = user,accesstoken = serializer.data['accesstoken'],socialid = serializer.data['socialid']).save()
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
else:
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)