How do you make a django field reference to a python class? - django

I am working on a project to expand a testing suite that my company uses. One of this things that was asked of me was to link the website to our Github source for code so that the dev team could continue tracking the issues there instead of trying to look in two places. I was able to do this but the problem is that every time the a bug is reported an issue is opened.
I want to add a field to my Django model that tracks an Issue object (from the github3.py wrapper) that is sent to Github. I want to use this to check if an Issue has already been created in Github by that instance of the BugReport and if it has been created, edit the Issue instead of creating another issue in Github that is a duplicate. Does Django have a something that can handle this sort of reference?
I am using Django 1.3.1 and Python 2.7.1
EDIT
I was able to figure my specific problem out using esauro's suggestions. However, as mkoistinen said, If this problem came up in a program where the work-around was not as easy as this one was, should an object reference be created like I had originally asked about or is that bad practice? and if it is okay to make an object reference like that, how would you do it with the Django models?

I'm the creator of github3.py.
If you want to get the issue itself via a number, there are a couple different ways to do this. I'm not sure how you're interacting with the API but you can do:
import github3
i = githbu3.issue('repo_owner', 'repo_name', issue_number)
or
import github3
r = github3.repository('repo_owner', 'repo_name')
i = r.issue(issue_number)
or
import github3
g = github3.login(client_key='client_key', client_secret='client_secret')
i = g.issue('repo_owner', 'repo_name', issue_number)
# or
r = g.repository('repo_owner', 'repo_name')
i = r.issue(issue_number)
otherwise if you're looking for something that's in an issue without knowing the number:
import github3
r = github3.repository('repo_owner', 'repo_name')
for i in r.iter_issues():
if 'text to search for' in i.body_text:
i.edit('...')

Related

How can I disable a Django cache?

I have written a small django app and in it I can upload some documents and at another point I can make a reference from a payment to the corresponding document. But my problem is that the list of documents is always outdated. But when I kill my gunicorn and start the webserver again, then the dropdown list with documents loads correctly and also shows the newest file uploads.
Do you have an idea why Django behaves like that?
Best regards
Edit: I just saw that I have to edit this question.
So I have this in my forms.py:
dms_objects = dmsdok.objects.all().order_by('-id')
choices_dms = []
for dms_obj in dms_objects:
choices_dms.append((dms_obj.id, dms_obj.dms_dok_titel))
And also I have this in the form:
zahlung_dok_pseudo_fk = forms.IntegerField(required=False, widget=forms.Select(attrs={'class':'form-control',}, choices= choices_dms), label='Zugehörigkeit Dokument')
I guess that this is what Willem means, but I do not know how I must change that.

django update_or_create(), see what got updated

My django app uses update_or_create() to update a bunch of records. In some cases, updates are really few within a ton of records, and it would be nice to know what got updated within those records. Is it possible to know what got updated (i.e fields whose values got changed)? If not, does any one has ideas of workarounds to achieve that?
This will be invoked from the shell, so ideally it would be nice to be prompted for confirmation just before a value is being changed within update_or_create(), but if not that, knowing what got changed will also help.
Update (more context): Thought I'd give more context here. The data in this Django app gets updated through various means (through users coming on the web site, through the admin page, through scripts (run from the shell) that populate data from a csv etc.). The above question is important mostly for the shell scripts that update data from csvs, hence a solution at the database/trigger/signal level may not be helpful here (I guess).
This is what I ended up doing:
for row in reader:
school_obj0, created = Org.objects.get_or_create(school_id = row[0])
if (school_obj0.name != row[1]):
print (school_obj0.name, '==>', row[1])
confirmation = input('proceed? [y/n]: ')
if (confirmation == 'y'):
school_obj1, created = Org.objects.update_or_create(
school_id = row[0], defaults={"name": row[1],})
Happy to know about improvements to this approach (please see the update in the question with more context)
This will be invoked from the shell, so ideally it would be nice to be
prompted for confirmation just before a value is being changed
Unfortunately, databases don't work like that. It's the responsibility of applications to provide this functionality. And django isn't an application. You can however use django to write an application that provides this functionality.
As for finding out whether an object was updated or created, that's what the return value gives you. A tuple where the second value is a flag for update or create

django error: 'DatabaseOperations' object has no attribute 'geo_db_type'

I have a django project that uses google maps. I wanted to create a GIS application using GeoDjango and Google Maps following this tutorial but went through several issues.
Now I'm stuck, although I decided to remove everything but django still throwing this error regardless I removed all the details related to GIS:
AttributeError: 'DatabaseOperations' object has no attribute 'geo_db_type'
I mean there is nothing at all that relate my django project (in the code) to GIS?!
I feel like installing GIS/postgres must have messed up the django default database system.
Any suggestions?
I think I will solve this problem by myself. I found two similar questions here in this place and no one solved them or gave a clear answer.
See this:
GeoDjango error: 'DatabaseOperations' object has no attribute 'geo_db_type'
Which means no clear solution and gotta get around it myself.
This post is thus closed.

Django doesn't read from database – no error

I just set up the environment for an existing Django project, on a new Mac. I know for certain there is nothing wrong with the code itself (just cloned the repo), but for some reason, Django can't seem to retrieve data from the database.
I know the correct tables and data is in the db.
I know the codebase is as it should be.
I can make queries using the Django shell.
Django doesn't throw any errors despite the data missing on the web page.
I realize that it's hard to debug this without further information, but I would really appreciate a finger pointing me to the right direction. I can't seem to find any useful logs.
EDIT:
I just realized the problem lies elsewhere. Unfortunately I can't delete this post with the bounty still open.
Without seeing any code, I can only suggest some general advice that might help you debug your problem. Please add a link to your repository if you can or some snippets of your database settings, the view which includes the database queries etc...
Debugging the view
The first thing I would recommend is using the python debugger inside the view which queries the database. If you've not used pdb before, it's a life saver which allows you to set breakpoints in your Python script and then interactively execute code inside the interpreter
>>> import pdb
>>> pdb.set_trace()
>>> # look at the results of your queries
If you are using the Django ORM, the QuerySet returned from the query should have all the data you expect.
If it doesn't then you need to look into your database configuration in settings.py.
If it does, then you must might not be returning that object to the template? Unlikely as you said the code was the same, but double check the objects you pass with your HttpResponse object.
Debugging the database settings
If you can query the database using the project settings inside settings.py from the django shell it sounds unlikley that there is a problem with this - but like everything double check.
You said that you've set up a new project on a mac. What is on a different operating system before? Maybe there is a problem with the paths now - to make your project platform independent remember to use the os.path.join() method when working with file paths.
And what about the username and password details....
Debugging the template
Maybe your template is referencing the wrong object variable name or object attribute.You mentioned that
Django doesn't throw any errors despite the data missing on the web
page.
This doesn't really tell us much - to quote the Django docs -
If you use a variable that doesn’t exist, the template system will
insert the value of the TEMPLATE_STRING_IF_INVALID setting, which is
set to '' (the empty string) by default.
So to check all the variables available to your template, you could use the debug template tag
{{ debug }}
Probably even better though is to use the django-debugging-toolbar - this will also let you examine the SQL queries your view is making.
Missing Modules
I would expect this to raise an exception if this were the problem, but have you checked that you have the psycopg module on your new machine?

Passing negative values as arguments to custom management commands in django

Like many others, I've been learning web development on django through building a test app. I've the basic models set up. I've populated a few of the tables with the absolute minimum data needed for further testing though using fixtures.
Now for a different table, I want to create data tuples through a custom management command which takes the required arguments. If this works as expected, I'll save the created data to the database by adding the --save option.
The syntax of the command is like this
create_raw_data owner_id temperature [--save]
where owner_id is required and temperature (in C) is optional. Within the Handle method, I'm using factory boy to create the raw_data with the given arguments etc.
I did have some issues but searching on SO, google, django docs etc, I've got the command working fine.
EXCEPT when I input a negative temperature...
Then I get the following error
Usage: C:\test\manage.py create_raw_data [options]
Creates a RawData object. Usage: create_raw_data owner_id temperature [--save]
C:\test\manage.py: error: no such option: -5
The code I have for parsing the args is like this
for index, item in enumerate(args):
if index == 0:
owner_id = int(item)
else index == 1:
temp = int(item)
I put a print(args) as the 1st line inside Handle but it seems the control is not even reaching here.
I'm not sure what is wrong... please help...
Thanks a lot
got the issue fixed so providing an answer to others who may come across this.
The issue was with parse_args method of optparse. I've read in a number of places that though optparse is deprecated and instead argparse is recommended, django recommends using optparse since that is what it uses. Long story short, the link at link suggested a few alternatives and using create_raw_data 1 -- -5 works as expected. So I did get a workaround. Thanks.